How to debug code with the Object Initializer format

1

Following some good practices that Visual Studio itself recommends, we are unable to debug values of an object one by one using the Object Initializer or Object Initializer. What is the best way to get around this?

Ex:

var myObject = new Object 
{ 
   Id = 1, 
   Nome = "Teste" 
}

In the format above, when we put the breakpoint in the Id line for example, it considers the code snippet as a whole.

    
asked by anonymous 29.08.2017 / 16:20

3 answers

3

Object initialization is a facilitator, if you want to debug this code you have to use the traditional style. It is true that Visual Studio could create a form for this, but today it does not, so if there is no plugin that treats it differently, there is no way. Make:

var myObject = new Objeto(); {
myObject.Id = 1;
myObject.Nome = "Teste";

In this way each boot will take place on a specific line and you can put breakpoint and walk step by step.

I changed the type name because Object already exists in .NET and does not have those members.

This can be configured:

    
29.08.2017 / 16:36
3

There is no way. Only seeing the values after they were inserted into the object (see image below) or initializing in the usual way, would be:

var myObject = new Object();     
myObject.Id = 1;
myObject.Nome = "Teste";

So you can follow line after line.

If you have filled properties with method returns, you can always enter the method using the F11 key and debug the method itself. Otherwise, it will hardly be necessary to follow the fill line by line.

    
29.08.2017 / 16:28
1

There is a concept within OO that says that the ideal is for your class to change itself, not externally. I suggest that in order to debug the code and respect this rule, use the constructor to initialize the values.

public class Object
{
    public Object(int id, string nome)
    {
        Id = id;
        Nome = nome;
    }

    public int Id { get; private set; }
    public string Nome { get; private set; }
}

var myObject = new Object(1, "teste");
    
29.08.2017 / 16:50