Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Constructors versus Initializors in C# [duplicate]

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?

like image 969
Daniel Gomez Rico Avatar asked Apr 19 '11 14:04

Daniel Gomez Rico


People also ask

What are initializers in C?

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).

What is initializer list in a constructor?

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.

How do you initialize a data member in a constructor?

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.

Are constructors used for initialization?

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.


2 Answers

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.

like image 82
RB. Avatar answered Oct 06 '22 00:10

RB.


The difference is probably that the second won't compile.

You are missing a default constructor, which it calls in your second example.

like image 31
Arcturus Avatar answered Oct 06 '22 00:10

Arcturus