24

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.

James
  • 80,725
  • 18
  • 167
  • 237
Samvel Siradeghyan
  • 3,523
  • 3
  • 30
  • 49

2 Answers2

17

There's absolutely no difference between the two examples.

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

ChrisF
  • 134,786
  • 31
  • 255
  • 325
  • @Samvel - The code will compile to the same IL, but the compiler can infer the brackets in this case. – ChrisF Dec 22 '10 at 10:56
  • But is it possible to assign new values to properties like that? For example, `Customer cust = _context.Customers.FirstOrDefault(c => c.Id == 1); cust{ Name = "NewName"} //error` I usually do it like this `cust.Name = "NewName"`. Just wondering if I could use same syntax as the above to update the properties – Haikal Nashuha Aug 19 '18 at 01:51
  • 1
    @HaikalNashuha no, that's not possible with the current syntax. – ChrisF Aug 22 '18 at 15:48
3

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