32

I use ReSharper everyday, and today I asked myself why ReSharper suggests "Use object initializer" when I do this :

MyClass myClass = new MyClass();
myClass.MyInt = 0;
myClass.MyString = string.Empty;

It gets replaced by :

MyClass myClass = new MyClass
{
    MyInt = 0, 
    MyString = string.Empty
};

Does this optimize the execution of my code, or is it just a matter of reformatting?

Personally, I like it. But sometimes I hate it, because of this :

Resharper

I can't do step-by-step debugging :(

HireThisMarine
  • 241
  • 5
  • 12
Wassim AZIRAR
  • 10,823
  • 38
  • 121
  • 174

2 Answers2

29

The second contains less characters and so is more compact to read. You don't have to repeat myClass 2 more times, and the initialization logic is in one block.

It is really a syntactic sugar that doesn't change a thing in the generated code. If you doesn't like it, you can always disable the warning on ReSharper.

A longer post on the advantages of using Object Initializers here:

Community
  • 1
  • 1
Cyril Gandon
  • 16,830
  • 14
  • 78
  • 122
  • I may have the opposite opinion on its readability and feel that the unnecessary syntactic composition more easily leads to cluttered indecipherable code (after resharping we have a fun trend of chains of complex initializers in a single param list, blech), but this is a great answer, with further reading and addressing full question, thanks. – kcar Mar 25 '15 at 15:00
6

You can do step-by-step debugging partially if initializers are function calls:

MyClass c = new MyClass() 
{
    MyInt = 3,
    MyString = GenerateString(9)
};

In this case, F11 will lead you straight into the GenerateString method.

EDIT: If initializers are simple values, then step-by-step debugging is meaningless anyway.

Zoran Horvat
  • 10,924
  • 3
  • 31
  • 43