These are just two acceptable equivalent syntax for instantiation of objects in C# with object initialization (you can't omit the parenthesis if you are just doing var cat = new Cat();
).
- since your class has no explicit constructor, a default parameter-less constructor is provided to the Cat class
new Cat {...}
allows to instantiate and initialize properties of the Cat object as a shortcut for new Cat() {...}
, calling the mentioned constructor.
The part about the constructor is important. If there is no implicit default constructor / explicit parameter-less constructor, then you cannot omit the parenthesis, and you'll have to provide parameters in them anyway :
public class Cat {
public string Name;
public int Age;
public Cat(string s) { // since I provide a constructor with parameter here, no parameterless constructor exists
Name = s;
}
}
// ...
void TestCat()
{
// compilation error : 'Cat'' does not contain a constructor that takes 0 arguments
//var badCat1 = new Cat { Name = "Felix", Age = 3} ;
//var badCat2 = new Cat() { Name = "Felix", Age = 3} ;
// works (but no way to remove parenthesis here, since there are parameters to pass to csontructor)
var goodCat = new Cat("Felix") { Age = 3 } ;
Console.WriteLine($"The cat {goodCat.Name} is {goodCat.Age} years old");
}
Special case : (which is used a lot for collections, list, dictionaries, etc...).
If a class T implements IEnumerable (i.e. has a IEnumerable
GetEnumerator() public function), and implements an Add method, then the object initializer will use the Add method with the collection on enumeration.
Example from https://blog.mariusschulz.com/2014/06/26/fun-with-custom-c-collection-initializers
Creation of special class "Points" which acts like a "List" with the initialization.
Note that this also uses the existing parameter-less constructor !
public class Points : IEnumerable<Point3D>
{
private readonly List<Point3D> _points;
public Points()
{
_points = new List<Point3D>();
}
public void Add(double x, double y, double z)
{
_points.Add(new Point3D(x, y, z));
}
public IEnumerator<Point3D> GetEnumerator()
{
return _points.GetEnumerator();
}
IEnumerator IEnumerable.GetEnumerator()
{
return GetEnumerator();
}
}
Used like that :
var cube = new Points
{
{ -1, -1, -1 },
{ -1, -1, 1 },
{ -1, 1, -1 },
{ -1, 1, 1 },
{ 1, -1, -1 },
{ 1, -1, 1 },
{ 1, 1, -1 },
{ 1, 1, 1 }
};