I am trying to create an object using c# object initializer. But that class already has a constructor with one argument as per the need and I dont have a need for a default construcor so I didn't provide one. Compiler too won't provide a default constructor when there is a user-provided constructor in the class.
Now the problem arises when I try to create an instance of this class using an object initializer:
public class Foo
{
public int Data { get; set; }
public Foo(int Data)
{
this.Data = Data;
}
}
I instantiate the class like this:
Foo f=new Foo { Data=10};
And now I'm getting a compile-time error:
"Foo does not contain a constructor that takes 0 argument"
I know the error, it's because of the lack of a default constructor. When I don't have a need for the default constructor why should I provide one just for using object initializer? So I am just wondering, is there is any other way (style, syntactically) I can use this object initializer without explicitly providing a default constructor?
I checked this MSDN link, it says if you have a PRIVATE default constructor in your class you can't use object initializer, but I dont have a private default constructor here.
If you already have a constructor accepting the argument you require to properly initialize the object, then why not use the proper constructor syntax?