C
C#2y 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
Angius2y 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
ValwexOP2y ago
Thanks, but how do I know whether to use one or the other?
Angius
Angius2y 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
mindhardt2y ago
Unless you use init, which complicates stuff a bit
palapapa
palapapa2y 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 User2y ago
Message Not Public
Sign In & Join Server To View
Accord
Accord2y 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.

Did you find this page helpful?