C
C#12mo ago
Valwex

❔ Initializing an object

Hello, what is the difference between these two lines?
var p = new Point() { X = 42, Y = 13 };
var p = new Point() { X = 42, Y = 13 };
and
var p = new Point(42, 13);
var p = new Point(42, 13);
I know that the first allows you to initiate an object, but I don't understand the difference
7 Replies
Angius
Angius12mo ago
First is initializer syntax, the second one uses a constructor And thus, requires a constructor The first one requires public properties, but a constructor isn't needed
Valwex
Valwex12mo ago
Thanks, but how do I know whether to use one or the other?
Angius
Angius12mo ago
If you have a constructor, you should probably use it If you only have properties, you can use the first one Or you can mix them Just... use what's needed, I guess Initializer syntax is basically shortcut for
var point = new Point();
point.X = 42;
point.Y = 13;
var point = new Point();
point.X = 42;
point.Y = 13;
mindhardt
mindhardt12mo ago
Unless you use init, which complicates stuff a bit
palapapa
palapapa12mo ago
Like what @mindhardt said, if you have a init only property, then it must be set either in the constructor or in the object initializer(your first example), and it can't be set afterwards.
Unknown User
Unknown User12mo ago
Message Not Public
Sign In & Join Server To View
Accord
Accord12mo ago
Was this issue resolved? If so, run /close - otherwise I will mark this as stale and this post will be archived until there is new activity.