C
C#16mo 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
Angius16mo 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
ValwexOP16mo ago
Thanks, but how do I know whether to use one or the other?
Angius
Angius16mo 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
mindhardt16mo ago
Unless you use init, which complicates stuff a bit
palapapa
palapapa16mo 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 User16mo ago
Message Not Public
Sign In & Join Server To View
Accord
Accord16mo 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.
Want results from more Discord servers?
Add your server