Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Matching constructor to counterpart in generic type definition

I have been thinking about this problem for a while and it feels like there must be a simple solution that I'm missing.

Let's say I have the following class:

public class Foo<T>
{
   public Foo(T value)
   {
   }

   public Foo(int value)
   {   
   }
}

If I get all constructors on the type Foo<System.Int32> I will get back two constructors, both with a single parameter of type System.Int32 which cannot be differentiated.

If I get all constructors from the generic type definition of Foo<System.Int32> (Foo<T>) I will get back two constructors. One which accepts a generic parameter T and one that accepts a parameter of type System.Int32

// Will return two constructors with signatures that look identical.    
var type = typeof(Foo<int>);    
var ctors1 = type.GetConstructors();

// Will return two constructors as well. Parameters can be differentiated.
var genericTypeDefinition = typeof(Foo<int>).GetGenericTypeDefinition();
var ctors2 = genericTypeDefinition.GetConstructors();

Is there a way to match a constructor to its counterpart in its generic type definition?

like image 375
Patrik Svensson Avatar asked Sep 01 '14 23:09

Patrik Svensson


1 Answers

For Comparing the ctors in both cases you can compare their MetadataToken. Example:

foreach (var item in ctors1)
{
    var ctorMatch = ctors2.SingleOrDefault(c => c.MetadataToken == item.MetadataToken);
}
like image 58
terrybozzio Avatar answered Nov 01 '22 18:11

terrybozzio