Why debugging Generics is a little different?

Well I am not going to describe what are generics and how they solve the problem of dealing with classic collections without costing type-safety and performance. I am sure most of you already know it. If not, you can find tons of information online. What I am going to talk today is how debugging generic types and method via WinDbg ( or other native debuggers) is a little different.

Let’s take following code as an example. Nothing crazy here, not the most useful code but its good enough to show the trick.

namespace DemoApp
{
 class Program
 {
 static MyType<int> IntType = new MyType<int>();
 static MyType<int,byte> IntByteType = new MyType<int, byte>();

 static void Main(string[] args)
 {
 IntType.ShowTypes();
 IntByteType.ShowTypes();
 }
 } 
 public class MyType<T>
 {
 private T t = default(T);
 public void ShowTypes()
 {
 Console.WriteLine(t.GetType().Name);
 }
 } 
 public class MyType<T1, T2>
 {
 private T1 t1 = default(T1);
 private T2 t2 = default(T2);
 public void ShowTypes()
 {
 Console.WriteLine(t1.GetType().Name + " - " + t2.GetType().Name);
 }
 }
}

We have two generic (overloaded) types here, each of which expose a method ShowTypes. Now let’s say we want to put a breakpoint on each of this method. In non-generic world, its very straighforward using bpmd command. However you will need to use a little trick when you want to add a breakpoint to a generic method. Reason is that CLR appends a `1 or `2 at the end of type name. This is done to differentiate between generic types that may exists with same name but different number of parameters. Let’s first open this assembly in JustDecompile and see what IL is generated for these generic types.

As mentioned before, CLR has appened `1 and `2 in these two types. Now let’s try it debug this code in WinDbg. I will setup break point on ShowTypes methods in both these types by using following two commands.

Once first breakpoint got hit, notice the stack trace. You can verify it by running CLRStack command also.

And when second breakpoint get hit, we can see its against the other type with two parametrs.

Until next, happy Debugging.

Advertisements
This entry was posted in .NET, Debugging. Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s