1

I was wondering if there are any way to put break point inside an automatic constructor/object initializer block?

Example:

var x = new Person()
{
  Name = 'John',
  Age = DateTime.Now - Birthdate
}

I want to put breakpoint on the 4th line. This is very helpful when setting like 150 fields with different logic for each property and the type you are creating an instance of is not under your control (e.g. EF4 entity), therefore you cannot create a custom constructor. Any ideas?

Ross Brigoli
  • 676
  • 1
  • 12
  • 22
  • possible duplicate of [How can I properly use breakpoints when using fancy object initializers](http://stackoverflow.com/questions/5112782/how-can-i-properly-use-breakpoints-when-using-fancy-object-initializers) – Michał Powaga Feb 16 '12 at 07:48
  • 1
    Nitpick - this is known as an object initializer. It is important to note that these properties are _not_ being set at construction time. They are being set immediately after construction. This is just syntactic sugar for creating the instance (using the default constructor in your example above) and then immediately assigning the properties. – Rob Levine Feb 16 '12 at 07:54
  • 1
    Nitpickier :) - With a difference: with object initializers, below the surface a temporary object is created that after setting all properties is copied to the visible object (person). The difference is that there is never a person object in an undefined state. – Gert Arnold Feb 16 '12 at 08:18
  • You cand mark some answer as the final one if it suits your needs :) It helps you receive good answers on your other questions. – Claudiu Constantin Mar 14 '12 at 19:24

4 Answers4

4

A workaround you can use for this issue is writing the code like this to ease your debugging:

var x = new Person();
x.Name = "John";
x.Age = DateTime.Now - Birthdate;
Claudiu Constantin
  • 2,138
  • 27
  • 38
1

Wrap the value on a line where you want a breakpoint in a self calling function:

var x = new Person() {
    Name = new Func<string>(() =>"John").Invoke(),
    Age = DateTime.Now - Birthdate
};

Now you will be able to "step into" it. It won't be of much use, though, as x will remain null until the end of the block.

user1096188
  • 1,809
  • 12
  • 11
1

If Name property is not automatic you can put a breakpoint inside set of that property.

Tigran
  • 61,654
  • 8
  • 86
  • 123
0

If your doing it that way then you can't. You can out a breakpoint on the entire block and step through it using F11.

Why dont you do the following

Person p = new Person();
p.Name = "John";
p.//Blah
MyKuLLSKI
  • 5,285
  • 3
  • 20
  • 39