开发者

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

This question already has answers here: 开发者_开发问答 Closed 12 years ago.

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.


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 ().

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜