When you pass an variable into an object during instantiation, such as in
SomeObject newObject = new SomeObject() { SomeString = "String goes here" };
Will the variable SomeString be accessible in the constructor or will it be assigned afterwards? If I needed to use it in the constructor, would it work or would I need to pass it through as a parameter using
new SomeObject("String goes here");
will the variable SomeString be accessible in the constructor, or will it be assigned afterwards?
It will be assigned afterwards.
SomeObject newObject = new SomeObject() { SomeString = "String goes here" };
is roughly equivalent/syntactic sugar to:
SomeObject temp = new SomeObject();
temp.SomeString = "String goes here";
SomeObject newObject = temp;
It will be assigned afterwards in the first case. NOTE: This requires there to be a parameterless constructor, which will exist by default, unless you define a parameterized constructor. In that case you must define both constructors explicitly.
For more detail you can look at details on Object Initializers.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With