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