Tuesday, September 11, 2012

Using parentheses with object initializers

public class ClassWithDefaultConstructor
{
    public string Property { get; set; }
}
public class ClassWithConstructorWithParameters
{
    public ClassWithConstructorWithParameters(string property)
    {
        this.Property = property;
    }
    public string Property { get; set; }
}
   
Correct usages -
var c = new ClassWithDefaultConstructor { Property = "value" };
var c = new ClassWithDefaultConstructor() { Property = "value" };
var c = new ClassWithConstructorWithParameters() { Property = "value" };
 
Wrong usage -
var c = new ClassWithConstructorWithParameters { Property = "value" };
 
Reason -
If you are using a parameterless constructor, as shown, the parentheses are optional, but if you are executing a constructor that requires parameters, the parentheses are mandatory, o/w, the compiler would cry as below -
 
Compile error -
'LINQProcessing.ClassWithConstructorWithParameters' does not contain a constructor that takes 0 arguments

PS: Please comment if this served your purpose by any chance. Happy coding :)

2 comments:

  1. Nice.. I do not know this before. Thanks for blogging it.
    - Rajesh

    ReplyDelete
  2. You are welcome Rajesh. Appreciate the feedback.

    ReplyDelete

Please help to make the post more helpful with your comments.