Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Use object initializer - Resharper suggestion

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 :(

like image 748
Wassim AZIRAR Avatar asked Dec 19 '13 13:12

Wassim AZIRAR


People also ask

Why use object initializer?

Besides, initializers are useful in multi-threading. Object initializers are used to assign values to an object's properties or fields at creation time without invoking the constructor. If you create an object and then right after that assign values to its properties, ReSharper suggests using an object initializer.

What is collection initializer?

C# - Object Initializer Syntax NET 3.5) introduced Object Initializer Syntax, a new way to initialize an object of a class or collection. Object initializers allow you to assign values to the fields or properties at the time of creating an object without invoking a constructor.

What is object initializer in C#?

In object initializer, you can initialize the value to the fields or properties of a class at the time of creating an object without calling a constructor. In this syntax, you can create an object and then this syntax initializes the freshly created object with its properties, to the variable in the assignment.


2 Answers

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:

  • Setting properties via object initialization or not : Any difference ?
  • Is there any benefit of using an Object Initializer?
like image 184
Cyril Gandon Avatar answered Oct 17 '22 01:10

Cyril Gandon


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.

like image 42
Zoran Horvat Avatar answered Oct 17 '22 02:10

Zoran Horvat