Anonymous Constructor in C#

C# 3.0 introduced a very compact way of initializing objects of a class.

Previously we used to initialize objects like this:

MailMessage mailMessage = new MailMessage();
            mailMessage.Body = message;
            mailMessage.BodyEncoding = Encoding.GetEncoding(UIConstants.NewAccountMailBodyEncoding);
            mailMessage.From = new MailAddress(UIConstants.Me2AdminEmail);

Now, with the new feature known as Anonymous Constructors or Object Intializers we can do the same code in C# 3.0 and above like this:

 MailMessage mailMessage = new MailMessage()
                Subject = UIConstants.UIErrorSubject,
                Body = message,
                BodyEncoding = Encoding.GetEncoding(UIConstants.NewAccountMailBodyEncoding),
                From = new MailAddress(UIConstants.Me2AdminEmail)

In the C# 3.0 code, there is no constructor that corresponds to the way I instantiated the object. This prevents developers from having to create a different constructor for each different set of properties that need to be set. It also make the code easier to read.

kick it on

Shout it

pimp it

Anky Goyal

I am MCPD certified in .NET and working on .NET technologies for past 3yrs. I am very passionate about the new features which get introduced in the technology. I am here to share the new features i get to know in the world of Microsoft. Follow me on twitter @ankygoyal [email protected]Ankit Goyal

More Posts - Website

  • Pingback:

  • Sean

    That’s called Object Initialization, not an anonymous constructor. C# 3.0 also added Collection Initialization.

    • Yes if one carefully reads the article object initializer is also mentioned in the article.

      And can u plzz tell an example of collection initializer and how are they useful?

  • I think what Sean is saying is, what you’ve described is only Object Initializers, not Anonymous Constructors. I.e. the constructor is named and any number of objects can be created and initialized because there is no anonymous constructor.

  • Sean

    @Ankit, here is a bit of information from the C# 3.0 language specification on Collection Initializers:

    The following is an example of an object creation expression that includes a collection initializer:
    List digits = new List { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 };
    The collection object to which a collection initializer is applied must be of a type that implements System.Collections.IEnumerable or a compile-time error occurs. For each specified element in order, the collection initializer invokes an Add method on the target object with the expression list of the element initializer as argument list, applying normal overload resolution for each invocation. Thus, the collection object must contain an applicable Add method for each element initializer.