44

During a debug session, it's important for me to identify the name of the actual derived class in the debug info of specific instances.

I tried using this.GetType().Name but this simply returns the type of the base class.

Is there a simple way to get the type of the derived class from within the base class?

ΩmegaMan
  • 29,542
  • 12
  • 100
  • 122

4 Answers4

64

this.GetType().Name should work. I think, in your case, you may not have a derived class. If it's returning the base class name, it shouldn't have a derived class.

Using this on:

  1. Base class - Outputs Base class name
  2. Derived class - Outputs Derived class name
  3. Derived class cast to Base class - Outputs Derived class name
  4. Derived class passed into a function that accepts Base class as a parameter - Outputs Derived class name
Community
  • 1
  • 1
n8wrl
  • 19,439
  • 4
  • 63
  • 103
15

this.GetType().Name always return the name of the current executing type, not the type that the code that it was written in. You can emulate breakpoints though, using Debugger.Break() in a conditional manner:

if (this.GetType().Name == "Problematic type")
    System.Diagnostics.Debugger.Break();
Cecil Has a Name
  • 4,962
  • 1
  • 29
  • 31
2

During a debug session...

Remember that instead halting a session to add some throw-away code to then recompile and restart, one can use the debugger to divine that after the breakpoint is hit...

By utilizing the Immediate Window of the debugger and typing a this.GetType().Name off of the instance in question and then pressing Enter, it will be shown.

See VS Docs: Immediate Window

Is there a simple way to get the type of the derived class from within the base class?

Yes, for an example I can determine what the exception is by using the Name property of GetType and in real time:

enter image description here

ΩmegaMan
  • 29,542
  • 12
  • 100
  • 122
0

When raising an event, be sure to pass the real sender to the sender property. The sender object in the listening class should correctly point to the child class that raised the event.

Pierre-Alain Vigeant
  • 22,635
  • 8
  • 65
  • 101