❔ Initializing an object
Hello, what is the difference between these two lines?
and
I know that the first allows you to initiate an object, but I don't understand the difference
7 Replies
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
Thanks, but how do I know whether to use one or the other?
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
Unless you use
init
, which complicates stuff a bitLike 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•17mo ago
Message Not Public
Sign In & Join Server To View
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.