How to use breakpoints correctly when using an object initializer?

For example, follow these steps:

foreach (DataRow row in data.Rows)
{
    Person newPerson = new Person()
    {
        Id = row.Field<int>("Id"),
        Name = row.Field<string>("Name"),
        LastName = row.Field<string>("LastName"),
        DateOfBirth = row.Field<DateTime>("DateOfBirth")
    };

    people.Add(newPerson);
}

It is not possible to set a breakpoint for a separate forwarding; a breakpoint is set on the entire block.

If I want to see where my code breaks, I should use:

 foreach (DataRow row in data.Rows)
 {
     Person newPerson = new Person();
     newPerson.Id = row.Field<int>("Id");
     newPerson.Name = row.Field<string>("Name");
     newPerson.LastName = row.Field<string>("LastName");
     newPerson.DateOfBirth = row.Field<DateTime>("DateOfBirth");

     people.Add(newPerson);
 }

Or maybe I missed something. Can you properly debug when using an object initializer?

+3
source share
1 answer

Object initializers are just syntactic sugar and translate when they are compiled. The initial initializer of the object will look something like this:

var temp = new Person();
temp.Id = row.Field<int>("Id");
temp.Name = row.Field<string>("Name");
temp.LastName = row.Field<string>("LastName");
temp.DateOfBirth = row.Field<DateTime>("DateOfBirth");
var person = temp;

, . , .

  • . , .

  • . Id = row.Field<int>("Id") row.Field<int>("Id") ( , ), .

  • . , . :

    Id = BreakThenDoSomething(() => row.Field<int>("Id"));

    public static T BreakThenDoSomething<T>(Func<T> f)
    {
        Debugger.Break();
        return f();
    }
+2

Source: https://habr.com/ru/post/1794602/


All Articles