Could someone please provide a explanation of Object Initialisers in C# and examples if possible.
So far I understand that they allow you to condense instances of a class, is this correct?
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
Object initializers was added to C# in version 3, and provide condensed object initialization syntax. They are nothing but syntactic sugar, meaning they allow you to express the same code shorter than before.
Here is an example:
Which is the equivalent of:
Have a look on the official documentation here.
A related feature is collection initializers, which lets you initialize collections easily:
The above code is short hand for constructing a new List, and then adding each element to it. For collection initializers to work for a type, nothing more is required than a
public Addmethod taking the correct type as the parameter.