Home

How does LINQPad's Dump decide which type to print?

Consider the following code:

List<int> l1 = new() { 3, 5, 6 };
List<int> l2 = new() { 1, 2 };

l1.Concat(l2).Dump();
l1.Concat(l2).GetType().Dump(); 

The return type for the Concat method is listed clearly in the docs https://learn.microsoft.com/en-us/dotnet/api/system.linq.enumerable.concat?view=net-8.0#returns which is IEnumerable<TSource>. LINQPad's Dump method shows this correctly - based on the type of elements in our lists Int32, as the first output seen below:

If I try to get this information myself, it doesn't go that well. First, using GetType will return the actual type of the object returned - Concat2Iterator<Int32> - highlighted in green below (link to code here). From my understanding this is called the runtime type.

If I try to use instead GetType().GetInterfaces() I do get the interfaces that the respective type Concat2Iterator<Int32> implements, but obviously there are multiple ones:

But how does LINQPad know to print only IEnumerable<Int32>~ as the type when invokingDump` in this case?

I feel like I'm missing a very basic thing here. I've looked through a couple of C# books I have - including an older version of "C# 7.0 in a Nutshell" - but I can't figure out what's the answer.

Comments

  • LINQPad is displaying the static type (i.e., the compile-time type) which it captures via the type parameter on Dump. It does a similar thing when enumerating fields and properties - it uses the field/property type as the static type.

  • Understood. I tried with the extension method below, and indeed it prints System.Collections.Generic.IEnumerable`1[System.Int32]. Processing this so it gets the short name of the types gets me to IEnumerable<Int32>, which I'm after. Thank you!

    public static class TypeExtensions
    {
        public static void DisplayStaticType<T>(this T obj)
        {
            Type staticType = typeof(T);
            Console.WriteLine($"The static type is: {staticType}");
        }
    }
    
Sign In or Register to comment.