Possible Duplicate:
Why are C# 3.0 object initializer constructor parentheses optional?
Hi all
I have a class Question
which has a property Text
public class Question
{
public string Text { get; set; }
}
Now I want to create an object of this type by giving value to property.
I can do that in this two ways:
Question q = new Question { Text = "Some question" };
and
Question q = new Question() { Text = "Some question" };
Is there any difference between this two cases and if they are the same, why we need both?
Thanks.
One way is to add a property using the dot notation: obj. foo = 1; We added the foo property to the obj object above with value 1.
The Object.assign() method copies all enumerable own properties from one or more source objects to a target object. It returns the modified target object.
After you have created an object, you can set or change its properties by calling the property directly with the dot operator (if the object inherits from IDL_Object) or by calling the object's SetProperty method.
In general, when we try to copy one object to another object, both the objects will share the same memory address. Normally, we use assignment operator, = , to copy the reference, not the object except when there is value type field. This operator will always copy the reference, not the actual object.
There's absolutely no difference between the two examples.
In this case, and in this case alone, the ()
on the constructor is optional.
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