Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

2 ways to create new object by setting property values [duplicate]

Tags:

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.

like image 937
Samvel Siradeghyan Avatar asked Dec 22 '10 10:12

Samvel Siradeghyan


People also ask

How do you add properties to an object?

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.

How do you copy properties from one object to another in JavaScript?

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.

What is called to change the properties of an 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.

How do I copy values from one object to another in C#?

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.


1 Answers

There's absolutely no difference between the two examples.

In this case, and in this case alone, the () on the constructor is optional.

like image 57
ChrisF Avatar answered Oct 20 '22 00:10

ChrisF