Reputation: 19
I'm beginner in C#.
Every time I created Constructor in my class to instantiate class.
class OtherClass
{
void Main()
{
MyClass myClass = new MyClass();
}
}
class MyClass
{
public string text;
public int num;
public MyClass()
{
text = "something";
num = 12;
}
}
But today i saw new variant for me
class OtherClass
{
void Main()
{
MyClass myClass = new MyClass { num = 12, text = "something" };
}
}
class MyClass
{
public string text;
public int num;
}
Can somebody explain difference?
P.S Sorry for my English.
Upvotes: 0
Views: 1391
Reputation: 62093
This is standard C#
- it creates the class and then assigns values to properties.
You should read the C#
language specs.
Technically this is identical to:
var myClass = new MyClass ();
myCVlass.num = 12;
myClass.text = "something";
Just syntactic sugar that i.e. VS will recommend you in code analysis automatically as simplified syntax.
The explanation in the documentation is under this link.
Upvotes: 5
Reputation: 9804
The first is a Constructor with a hardcoded set of values. So not really that usefull. You want to have the Constructor take the values in as arguments. Anything else rarely usefull.
The 2nd thing is the Object Initializer. It works similar to the array initializer, in that it is just shorthand/syntax sugar for work. The Initializer is just a bunch of normal assignments to public variables/setters.
There are a number of cases (readonly Fields, private fields, private setters) where only the constructor can write something. The Object Initializer has no access to it. It really is only shorthand.
The 2nd thing of confusing might be the implicit Constructor. If you do not provide a constructor, a implicit, parameterless constructor is automagically created. This one will vanish once you define any constructor, as in that case you might not want the automatic one anymore. Sometimes there intentionally is no parameterless or even public constructor. In your case
class MyClass
{
public string text;
public int num;
}
absolutely has a Parameterless constructor MyClass()
.
Upvotes: 0