C# Object initializer without default constructor

3.7k views Asked by At

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.

3

There are 3 answers

0
Allon Guralnek On BEST ANSWER

If you already have a constructor accepting the argument you require to properly initialize the object, then why not use the proper constructor syntax?

Foo f = new Foo { Data = 10 };  // What you want (object initializer syntax)
Foo f = new Foo ( Data : 10 );  // What you can get (constructor syntax)
0
levelnis On

Then don't use the object initialiser. Just pass the value in via the constructor:

Foo f=new Foo(10);

If you want to use the object initialiser, you can:

Foo f=new Foo(10){ Data=10};

But you are setting the same value twice so there's no point

0
Mathieu Guindon On

The object initializer syntax is shorthand for something like this:

var x = new MyClass();
x.Property1 = "value1";
x.Property2 = "value2";
x.Property3 = "value3";
...

You can verify this by creating a default constructor with dummy content and a breakpoint, and then instantiating the class with an object initializer; the breakpoint will be hit, even though you're not explicitly calling the default constructor.

So when you do var x = new MyClass { Property1 = "value1", Property2 = "value2, Property3 = "value3" };. you are calling the default constructor. If it's missing, you get the compile-time error you noticed.