Ayende @ Rahien

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

ayende@ayende.com

+972 52-548-6969

@

Posts: 5,947 | Comments: 44,541

filter by tags archive

Generics Challage: Assert Return Types Matches


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

No future posts left, oh my!

RECENT SERIES

  1. RavenDB Sharding (3):
    22 May 2015 - Adding a new shard to an existing cluster, splitting the shard
  2. The RavenDB Comic Strip (2):
    20 May 2015 - Part II – a team in trouble!
  3. Challenge (45):
    28 Apr 2015 - What is the meaning of this change?
  4. Interview question (2):
    30 Mar 2015 - fix the index
  5. Excerpts from the RavenDB Performance team report (20):
    20 Feb 2015 - Optimizing Compare – The circle of life (a post-mortem)
View all series

RECENT COMMENTS

Syndication

Main feed Feed Stats
Comments feed   Comments Feed Stats