Ayende @ Rahien

Hi!
My name is Oren Eini
Founder of Hibernating Rhinos LTD and RavenDB.
You can reach me by phone or email:

ayende@ayende.com

+972 52-548-6969

, @ Q c

Posts: 6,128 | Comments: 45,548

filter by tags archive

Generics Challage: Assert Return Types Matches

time to read 13 min | 2573 words

I feel that I gave it too much already, and I am giving up. A workaround is too good for this issue.

Given the following class defination:

public class Dog

{

       public static MethodInfo LastCall = null;

       public class BarkInvocation<T>

       {

              public T Bark()

              {

                     LastCall = (MethodInfo)MethodInfo.GetCurrentMethod();

                     return default(T);

              }

       }

 

       public T Bark<T>()

       {

              return new BarkInvocation<T>().Bark();

       }

}

Can you make this print true?

public class Program

{

       [STAThread]

       static void Main(string[] args)

       {

              Dog d = new Dog();

              d.Bark<IList<string>>();

              Type returnType = Dog.LastCall.ReturnType;

 

              List<string> strings = new List<string>();

 

              Console.WriteLine(returnType.IsInstanceOfType(strings));

       }

}

 


Comments

Weex

IList is not an instance of List, isn't it?

Doug Mayer

Wow, this is a good one. The method's return type will always be T, because at runtime it's resolved from System.RuntimeType.

The only way I'd know of is to also have a LastReturnType static field on Dog and set it to typeof(T) in BarkInvocation.Bark()... which I'm sure there's a reason you're not already doing (I know I hate to add what I feel are more fields that aren't required).

@Weex,

If you do a test as I mention above, you'll see that just calling

typeof(IList).IsInstanceOf(new List());

will return true.

Comment preview

Comments have been closed on this topic.

FUTURE POSTS

  1. The low level interview question - 7 hours from now
  2. The worker pattern - 3 days from now

There are posts all the way to May 30, 2016

RECENT SERIES

  1. The design of RavenDB 4.0 (14):
    26 May 2016 - The client side
  2. RavenDB 3.5 whirl wind tour (14):
    25 May 2016 - Got anything to declare, ya smuggler?
  3. Tasks for the new comer (2):
    15 Apr 2016 - Quartz.NET with RavenDB
  4. Code through the looking glass (5):
    18 Mar 2016 - And a linear search to rule them
  5. Find the bug (8):
    29 Feb 2016 - When you can't rely on your own identity
View all series

RECENT COMMENTS

Syndication

Main feed Feed Stats
Comments feed   Comments Feed Stats