Take the 2-minute tour ×
Programmers Stack Exchange is a question and answer site for professional programmers interested in conceptual questions about software development. It's 100% free, no registration required.

What is it called when you set properties on object initialization?

var customer = new Customer() {RequestID = request.ID, AddressID = 5};

Is it considered good practice?

share|improve this question
3  
It's just a convenient syntax, but notice how well your example reads. By the way, you don't need the parentheses. –  Robert Harvey Sep 28 '11 at 16:28
    
@Robert Harvey your right. Neat –  Tom Squires Sep 28 '11 at 18:55
add comment

7 Answers 7

up vote 10 down vote accepted

It's called object initializer or object initialization expressions, in C# at least. Its implementation was necessary for LinQ, to dynamically create anonymous types in a convenient manner.

Whether it's a good practice or not depends on how you use it. Read Jon Skeet's thoughts about them on stackoverflow to gain some more insight. Jimmy Hoffa also wrote an excellent answer on codereview. He proposes to base the decision for or against object initializers on the question:

Is the object safely usable if the properties are null?

If so, then object initializers provide a very convenient and readable way to create an object.

share|improve this answer
    
The object cant be used if they are null. However as its a datacontract it has to be mutable anyway. –  Tom Squires Sep 28 '11 at 18:58
    
@Tom Squires: How many properties have you got? If it's a significant amount (more than 5 for my personal taste) don't enforce their initialization via a constructor, as it'd just be a pain to use and maintain these constructors. I've had these cases in which the constructor took 10 arguments and the compiler kept complaining because I didn't meet the signature (and couldn't see why for 10 minutes) or the constructor lacked validations anyway, which made the whole intent rather pointless. –  Falcon Sep 28 '11 at 21:02
    
@Tom Squires: Just set them via an initializer or traditionally and add a Unit test or put the validation elsewhere, for example in the object which processes the data and have that object throw an exception. In many cases that is just as good. –  Falcon Sep 28 '11 at 21:03
    
@Tom Squires: Another factor that just came to my mind is: Does the object need these values to maintain its own integrity or is this integrity only important to something external. If the integrity is only important to something external, then have the validation there. In the end, the most important thing are meaningful error messages, so you can trace the fault quickly. –  Falcon Sep 28 '11 at 21:33
add comment

To add a bit to Falcon's good answer:

What is the name for setting properties when an object is instantiated?

It is an "object initializer". Note that the equivalent feature for collections is called a "collection initializer". That is, you can also say

x = new List<int>() { 10, 30, 20 };

and that will be translated into

var temp = new List<int>();
temp.Add(10);
temp.Add(30);
temp.Add(20);
x = temp;

for you. You can even mix object and collection initializers! See the C# specification section 7.6.10.3 for an example of how to use a collection initializer inside an object initializer.

Is it considered good practice?

We didn't add it to C# 3.0 because it was a bad practice!

The compelling benefit of object and collection initializers is not just that they are a much more compact, less "ceremonial" way to create and initialize an object. The compelling benefit is also that an object initializer is an expression, not a collection of statements. That means that you can use them in contexts where expressions are legal but statements are not, like:

  • field and local initializers
  • array initializers
  • expression lambdas
  • LINQ query comprehensions
  • and so on
share|improve this answer
add comment

Yes, it's good practice. It's more readable because you don't have the repetition of customer. and =. It may seem like a minor point, but it takes time and energy to scan those lines and verify that indeed they are all initializing customer.

And consider this:

var customer1 Customer();
customer1.RequestId = request.id1;
customer1.AddressId = 3;
customer1.Name = 'Nick Nicely'

var customer2 = new Customer();
customer2.RequestId = request.id2;
customer2.AddressId = 5;
customer1.Name = 'Poor Nick!'

Repetitive code is prone to cut-and-paste errors. It's much better to express a simple thought (Create a new customer) in a single sentence (line of code) whenever possible.

share|improve this answer
add comment

Is it considered good practice?

I would suggest that it's not "bad" practice, being that it's mainly just a convenience feature. There is no difference between

var customer = new Customer() {RequestID=request.ID, AddressID = 5 };

or

var customer = new Customer();
customer.RequestId = request.ID;
customer.AddressID = 5;

Other than ceremony.

share|improve this answer
add comment

It's a nice bit of syntactic sugar and isn't really "good" or "bad" practice so much as it is a matter of style. The approach you should always go for is what improved readability.

Generally I will use this form whenever assignments are straightforward, whenever an assignment becomes more than giving in a value or a possibly a value and a quick trim() I will take it out and assign it to the object explicitly.

I also find it's helpful when I have to make a larger number of assignments and do it like:

var customer = new Customer(){
    RequestID = request.ID,
    AddressID = 5,
    Firstname = "Bob",
    Lastname = "Jones",
    FavouriteColor = "Blue",
    someOtherProperty = "Maybe"
}

I find the indentation and codeblock brackets just help make it more explicit and easier to skim through your code.

share|improve this answer
add comment

It's new with VS2008. If you need to write portable code that also compiles under VS2005 and earlier mono, refrain from using it.

share|improve this answer
add comment

Be wary of using Object Initializer syntax with anything other than simple values.

If you start having complex calls as part of the value initialisations it can be very hard to debug as an error in one of the value calls can be reported in the Constructor call and it's much harder to workout which value is actually causing the problem.

share|improve this answer
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.