How can I properly use breakpoints when using an object initializer?

867 Views Asked by At

For example, doing something like this:

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);
}

Setting a breakpoint to an individual assignation is not possible, the breakpoint is set to the entire block.

If I want to see specifically where my code is breaking, I have to 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'm missing something. Can you properly debug when using an object initializer?

2

There are 2 best solutions below

2
On BEST ANSWER

Object initializers are just syntactic sugar and get translated when they're compiled. Your original object initializer becomes 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;

Since the whole block is translated like that you can't break inside one step. If you absolutely need to break on one particular step, you have a few options.

  1. Break it up. Don't use object initializers while debugging, and you can put them back afterwords.

  2. Temp variables. Instead of assigning Id = row.Field<int>("Id") directly, assign row.Field<int>("Id") to a temp variable first (or whichever one you want to debug) and then assign the temp variable to the object initializer property.

  3. Method call. You can wrap some of the code in a custom method call solely to allow you to add a breakpoint within your custom method. You could even generalize it like this:

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

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

I opened an issue at https://developercommunity.visualstudio.com/t/Need-to-be-able-to-add-debugger-break-po/1109823 in 2016 and it is under consideration but will be implemented if community wants it.

No upvotes from community. Looks like most of them are ok with work-around.