Possible Duplicate:
What's the difference between an object initializer and a constructor?
In c# you can construct an object like:
public class MyObject{
int val1;
int val2;
public MyObject(int val1, val2){
this.val1 = val1;
this.val2 = val2;
}
}
With:
MyObject ob = new MyObject(1,2);
or with:
MyObject ob = new MyObject(){ val1 = 1, val2 = 2 };
What is the diference between that kind of constructors?
Initializer. In C/C99/C++, an initializer is an optional part of a declarator. It consists of the '=' character followed by an expression or a comma-separated list of expressions placed in curly brackets (braces).
Initializer List is used in initializing the data members of a class. The list of members to be initialized is indicated with constructor as a comma-separated list followed by a colon. Following is an example that uses the initializer list to initialize x and y of Point class.
Const member variables must be initialized. A member initialization list can also be used to initialize members that are classes. When variable b is constructed, the B(int) constructor is called with value 5. Before the body of the constructor executes, m_a is initialized, calling the A(int) constructor with value 4.
A constructor is used to initialize the state of an object. A method is used to expose the behavior of an object. A constructor must not have a return type. A method must have a return type.
MyObject ob = new MyObject(){ val1 = 1, val2 = 2 };
is just syntactic sugar (i.e. shorthand) for
MyObject ob = new MyObject();
ob.val1 = 1;
ob.val2 = 2;
One difference between the two is that you can set readonly fields from the constructor, but not by using the shorthand.
A second difference is that a constructor with parameters forces the client to provide those values. See Constructor-injection vs. Setter injection for a good bit of background reading.
The difference is probably that the second won't compile.
You are missing a default constructor, which it calls in your second example.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With