2 ways to create new object by setting property values [duplicate]
Possible Duplicate:
Why are C# 3.0 object initializer constructor parentheses optional?
Hi all
I have a classQuestion
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.There's absolutely no difference between the two examples.
In this case, and in this case alone, the ()
on the constructor is optional.
Use ()
in case if you require to pass argument to the constructor.
Else it will not create any difference...
They both are important as in case if you add any constructor in Question Class then you need to pass args, that is possible using ()
.
精彩评论