I have a type that uses generics. Let's call it FlowerDescriptor<T> some flowers are described using numbers, others using strings etc.
so FlowerDescriptor<int>; FlowerDescriptor<string>; etc
I want a mechanism (probably extension methods) for doing 2 things
seeing if something is a FlowerDescriptor and
seeing what the descriptor is.
I.e.
FlowerDescriptor<string>.GetType().IsFlowerDescriptor == true
string.GetType().IsFlowerDescriptor == false.
equally I might derive from FlowerDescriptor<int> i.e. class NumberedFlower: FlowerDescriptor<int>
new NumberedFlower.GetType().IsFlowerDesriptor == true;
as above but returns the type
FlowerDescriptor<string>.GetType().GetFlowerDescriptor() == typeof(string)
FlowerDescriptor<int>.GetType().GetFlowerDescriptor() == typeof(int)
new NumberedFlower.GetType().GetFlowerDescriptor() == typeof(int)
I have played about with variations of IsAssignableFrom and it feels like that ought to work with typeof(FlowerDescriptor<>).IsAssignableFrom(typeof(FlowerDescriptor<string>))
but it doesn't work. If it add the generic type however it does.
I am currently exploring GetInterfaces to know available interfaces. It'd be great to actually understand what I am doing wrong too..
Unless you want to add interfaces into the mix, the only choice you have is to
Detect that the type is actually a FlowerDescriptor<T>
or detect that the type inherits from something that is a FlowerDescriptor<T>
Unfortunately I don't think you can use IsAssignableFrom when it comes to open generics which means we're left with walking the inheritance chain up to the base classes.
Here is an example piece of code that would do the right thing:
public static bool IsFlowerDescriptor(this Type type)
{
if (type.IsGenericType && type.GetGenericTypeDefinition() == typeof(FlowerDescriptor<>))
return true;
if (type.BaseType != null)
return type.BaseType.IsFlowerDescriptor();
return false;
}
Here's a .NET Fiddle you can experiment with.
I would not expect the string or int class to know if its a descriptor, it makes a lot more sense to get that information from the FlowerDescriptor.
That being said if you want to use reflection you could get the generic type definition from the FlowerDescriptor instance
FlowerDescriptor<int> f = new FlowerDescriptor<int>();
Type t = f.GetType();
Type[] typeArguments = t.GetGenericArguments();
//check if type you care about is in typeArguments
Here is how you would get those two values:
bool isFlowerDescriptor = x is FlowerDescriptor<object>;
Type descriptorType = x.GetType().GetGenericArguments()[0];
You could wrap these in extension methods if you like. And add null-checks etc.
You might consider having a non-generic base class. Then your structure could look like:
public abstract class FlowerDescriptor { }
public class FlowerDescriptor<T> : FlowerDescriptor { }
public class NumberedFlower : FlowerDescriptor<int> { }
Your 2 extensions would be:
public static class Extensions
{
public static bool IsFlowerDescriptor(this object o)
{
return o is FlowerDescriptor;
}
public static Type GetFlowerDescriptor<T>(this FlowerDescriptor<T> o)
{
return typeof (T);
}
}
and you'd use it like:
public static void Main()
{
Console.WriteLine(new NumberedFlower().IsFlowerDescriptor()); //true
Console.WriteLine(new NumberedFlower().GetFlowerDescriptor()); //System.Int32
}
Generics have an adverse effect when it comes to reflecting over and comparing types, because a FlowerDescriptor<int> is a different type from FlowerDescriptor<string>. This is something I have not found a good rhythm for.
Related
I need to test if a value is an instance of a generic base class, without knowing the generic type parameter. Using the MSDN example as the base of my example, this is what I'd like to accomplish:
using System;
public class Class1<T> { }
public class DerivedC1 : Class1<int> { }
class IsSubclassTest
{
public static void Main()
{
Console.WriteLine(
"DerivedC1 subclass of Class1: {0}",
typeof(DerivedC1).IsSubclassOf(typeof(Class1<>)) // <- Here.
);
}
}
While this is syntactically correct, it always yields false. If I remove the generic type parameter, it works as expected (returns true).
How can I test if a class type is a subclass of a generic base class, without knowing its generic type parameter as such?
The problem is that DrevidedC1 is not a sublcass of Class1<T>, it's a subclass of Class1<int>. Make sure you understand this subtle diference; Class1<T> is a open type (T can be anything, it hasn't been set) while DerivedC1 extends a closed type Class1<int> (it's not open in T anymore, T is set to int and only int). So when you do the following:
typeof(DerivedC1).IsSubclassOf(typeof(Class1<>))
The answer is evidently false.
What you need to do is check if the generic type definition of DerivedC1's base type (think of it as the corresponding open generic type of Class1<int>) equals Class1<T> which it clearly does.
The correct code is therefore:
typeof(DerivedC1).BaseType.GetGenericTypeDefinition() == typeof(Class1<>));
Or better yet, as Matías Fidemraizer states in his answer:
typeof(DerivedC1).BaseType.GetGenericTypeDefinition().IsAssignableFrom(typeof(Class1<>)));
There's special methods on Type for this sort of thing. As far as I can see, you'll need to walk up your base-types and check each in turn until you either (a) hit a match or (b) get to the top of the inheritance hierarchy (i.e. System.Object).
As such, the following (recursive) extension method:
public static class TypeExtensions
{
public static bool IsDerivedFromGenericParent(this Type type, Type parentType)
{
if(!parentType.IsGenericType)
{
throw new ArgumentException("type must be generic", "parentType");
}
if(type == null || type == typeof(object))
{
return false;
}
if(type.IsGenericType && type.GetGenericTypeDefinition() == parentType)
{
return true;
}
return type.BaseType.IsDerivedFromGenericParent(parentType)
|| type.GetInterfaces().Any(t=>t.IsDerivedFromGenericParent(parentType));
}
}
will allow you to do the following
typeof(DerivedC1).IsDerivedFromGenericParent(typeof(Class1<>))
...and will also work if you test something derived from DerivedC1.
Changing typeof(DerivedC1).IsSubclassOf(typeof(Class1<>)) to typeof(Class1<>).IsAssignableFrom(typeof(DerivedC1).BaseType.GetGenericTypeDefinition()) should be enough in your case.
Type.IsAssignableFrom is more powerful than using Type.IsSubClassOf because it just checks if some type is assignable to other type. This includes, the same type, interface types and other cases.
public class BaseGenericType<T>
{
}
public class SubGenericType<T>: BaseGenericType<List<T>>
{
}
I have two generic types above, which one inherits from another but is still generic.
The strange thing I can't figure out is that typeof(SubGenericType<>).IsSubclassOf(typeof(BaseGenericType<>)) returns false. And typeof(SubGenericType<>).IsSubclassOf(typeof(BaseGenericType<List<>>)) still returns false. I've tried GetGenericTypeDefinition() and MakeGenericType() and GetGenericArguments() to check the inheritance, still not working. But typeof(SubGenericType<int>).IsSubclassOf(typeof(BaseGenericType<List<int>>)) returns true.
What I want is to get all classes by reflection then grab the specific class which inherits from a generic type passed in.
e.g.
(1)List<int> -->
(2)get generic type definition ==> List<T> -->
(3)make generic ==> BaseGenericType<List<T>> -->
(4)find subclass ==> SubGenericType<T>
(5)make generic ==> SubGenericType<int>
In step (4) I find nothing although I actually have that SubGenericType<T>. Why is that?
Once I wrote this method to check generic type inheritance:
static bool IsSubclassOfOpenGeneric(Type generic, Type toCheck)
{
while (toCheck != null && toCheck != typeof(object))
{
var cur = toCheck.IsGenericType ? toCheck.GetGenericTypeDefinition() : toCheck;
if (generic == cur)
{
return true;
}
toCheck = toCheck.BaseType;
}
return false;
}
This returns true:
IsSubclassOfOpenGeneric(typeof(BaseGenericType<>), typeof(SubGenericType<int>))
It doesn't check interfaces though.
By the way, usually if you have relations like this, and you write all the classes yourself, consider using interfaces. It is much easier to handle. You can for instance have a IGenericType interface without generic argument. Sometome you just do not care about the generic type and just want to access members which do not depend on the generic type. Sometimes you want to simply check if it is one of those. And you can use type variance.
Finally, I figured it out.
This is the very solution. To explain in details, I have to introduce some non-abstract coding:
It's about a value converter. My purpose is simple, to let users add their own value converters. In the conversion step, I will check built-in types' converters first(as IConvertible), if not found, I'll first search the current executing assembly for all custom converter classes that inherit a specific abstract class provided by me. And an interface is implemented by that abstract class to make constraint for later reflection. Then I filter those reflected classes for the one that matches.
Here is the base class and interface(all nested):
private interface ICustomConverter
{
Type SourceType { get; }
object CallConvert(string input);
}
public abstract class CustomConverter<T> : ICustomConverter
{
public abstract T Convert(string input);
public Type SourceType
{
get { return typeof (T); }
}
object ICustomConverter.CallConvert(string input)
{
return Convert(input);
}
}
I've made the interface private in the parent class and implemented explicitly. So that the method CallConvert() won't be called outside.
The generic parameter T is the Type to convert the string value to.
e.g.
public class Int32Converter:CustomConverter<int>
{
}
This is easy to handle since the conversion target type isn't generic. all I need to do is to get all types that implement ICustomConverter, and make a generic type from CustomConverter<T> with the given int, thus CustomConverter<int>. Then I filter those classes for the one that derives from CustomConverter<int>, and here I found Int32Converter.
Later I came across this situation:
public class ListConverter<T>:CustomConverter<List<T>>
{
}
and
public class DictConverter<T,U>:CustomConverter<Dictionary<T,U>>
{
}
I used the same process to deal with them. But after I made a generic type CustomConverter<List<T>>, I found that ListConverter<T> does not derive from CustomConverter<List<T>> and CustomConverter<List<T>> is not assignable from
ListConverter<T>(which I checked with IsAssignableFrom() and IsSubclassOf()).
I guess the reason is that generic type stands for more than one type before the generic parameters are assigned.
This sounds weird but it is true. The compiler doesn't know that the T in CustomConverter<List<T>> and ListConverter<T> stand for the same TYPE
In fact, I can write it like CustomConverter<List<T>> and ListConverter<U>, and then you tell me the inheritance relationship between them.
And base type checking won't work here since ListConverter<T> and DictConverter<T,U> share the same root class. This means if I look for ListConverter<T>, I'll get DictConverter<T,U> too with the base class checking method(hierarchy loop checking). So I still have to make generic type, then check generic arguments and do type comparing.
The point is that I need to look for the specific class whose generic parameters are used as the generic arguments in its parent class's generic parameter. Sort of twisted but now it is clear.
Here is the final Convertion solution:
public static object ToObject(Type type, string value)
{
if (type == null)
throw new ArgumentNullException("type");
if (!typeof (IConvertible).IsAssignableFrom(type))
{
if (type.IsGenericType)
{
Type converterType = typeof (CustomConverter<>).MakeGenericType(type);
Type genericConverter =
typeof (ICustomConverter).Assembly.Types(Flags.Public)
.SingleOrDefault(
t =>
typeof (ICustomConverter).IsAssignableFrom(t) && t.IsGenericType &&
t.GetGenericArguments().Length == type.GetGenericArguments().Length && !t.IsAbstract &&
t.MakeGenericType(type.GetGenericArguments()).IsSubclassOf(converterType));
if (genericConverter != null)
{
Type customConverter = genericConverter.MakeGenericType(type.GetGenericArguments());
object instance = customConverter.CreateInstance();
if (instance is ICustomConverter)
return ((ICustomConverter) instance).CallConvert(value);
}
}
else
{
Type converterType = typeof (CustomConverter<>).MakeGenericType(type);
Type customConverter =
typeof (ICustomConverter).Assembly.Types(Flags.Public)
.SingleOrDefault(t => t.IsSubclassOf(converterType));
if (customConverter != null)
{
object instance = customConverter.CreateInstance();
if (instance is ICustomConverter)
return ((ICustomConverter) instance).CallConvert(value);
}
}
throw new ArgumentException("type is not IConvertible and no custom converters found", type.Name());
}
TypeConverter converter = TypeDescriptor.GetConverter(type);
return converter.ConvertFromString(value);
}
I also checked GetGenericArguments().Length in case List<T> messes with Dictionary<TKey,TValue>.
Note: some custom extension methods are used.
Say I have the following class:
public class General<T> { }
And I want to find out if an object is of that type.
I know I can use reflection to find out whether the object is of that generic type with Type.GetGenericTypeDefinition, but I want to avoid that.
Is it possible to do something like obj is General<T>, or obj.GetType().IsAssignableFrom(typeof(General<T>))?
I'm quite surprised that I couldn't find a similar question, although I may have used wrong keywords in my searches.
You can do this:
var obj = new General<int>();
var type = obj.GetType();
var isGeneral =
(type.IsGenericType && type.GetGenericTypeDefinition() == typeof(General<>)) ||
type.GetBaseTypes().Any(x => x.IsGenericType &&
x.GetGenericTypeDefinition() == typeof(General<>));
Where GetBaseTypes is the following extension method:
public static IEnumerable<Type> GetBaseTypes(this Type type)
{
if (type.BaseType == null) return type.GetInterfaces();
return new []{type}.Concat(
Enumerable.Repeat(type.BaseType, 1)
.Concat(type.GetInterfaces())
.Concat(type.GetInterfaces().SelectMany<Type, Type>(GetBaseTypes))
.Concat(type.BaseType.GetBaseTypes()));
}
credits to Slacks answer
There are many answers to similar questions, but they all require reflection to walk up the type hierarchy. I suspect there is no better way. If performance is critical, caching the result maybe an option. Here is an example using a ConcurrentDictionary as a simple cache. Then the cost is reduced to a simple type lookup (via GetType) and a ConcurrentDictionary lookup after the cache has been initialized.
using System.Collections.Concurrent;
private static ConcurrentDictionary<Tuple<Type,Type>, bool> cache = new ConcurrentDictionary<Tuple<Type,Type>, bool>();
public static bool IsSubclassOfRawGeneric(this Type toCheck, Type generic) {
var input = Tuple.Create(toCheck, generic);
bool isSubclass = cache.GetOrAdd(input, key => IsSubclassOfRawGenericInternal(toCheck, generic));
return isSubclass;
}
private static bool IsSubclassOfRawGenericInternal(Type toCheck, Type generic) {
while (toCheck != null && toCheck != typeof(object)) {
var cur = toCheck.IsGenericType ? toCheck.GetGenericTypeDefinition() : toCheck;
if (generic == cur) {
return true;
}
toCheck = toCheck.BaseType;
}
return false;
}
And you would use it like this:
class I : General<int> { }
object o = new I();
Console.WriteLine(o is General<int>); // true
Console.WriteLine(o.GetType().IsSubclassOfRawGeneric(typeof(General<>))); //true
Generic type definitions that are instantiated with type parameters have no relation at all to other generic type instantiations. They also have no relation to the generic type definition. They are completely incompatible when it comes to assignment and runtime casting. If they weren't it would be possible to break the type system.
For that reason runtime casts will not help. You will indeed have to resort to Type.GetGenericTypeDefinition. You can abstract that into a helper function and keep your code relatively clean that way.
If a generic class or interface has members which could be used by code which held a reference in a more general form like Object but didn't have the actual generic type available, such members should be exposed in a non-generic base class or interface. The Framework has in many cases failed to abide by that principle, but there's no reason one must follow their example. For example, a type like IList<T> could have derived from IListBase which included or inherited members like:
int Count {get;}
void Delete(int index);
void Clear();
void Swap(int index1, int index2);
int Compare(int index1, int index2);
// Return an object with a `StoreToIndex(int)` method
// which would store it to the list it came from.
ListItemHolder GetItemHolder(int index);
ListFeatures Features {get;}
None of those members would rely in any way upon the type of items held within the list, and one could write methods to do things like sort a list (if its Features indicated that it was writable and knew how to compare items) without having to know anything about the element type. If a generic interface inherits from a non-generic interface, code needing the non-generic functions could simply cast to the non-generic interface type and use it directly.
For a more generalized solution, that works with any parent type (base class as well as interfaces):
public static bool IsCompatibleWith(this Type type, Type parentType)
{
if (type == null)
{
throw new ArgumentNullException(nameof(type));
}
if (parentType.IsAssignableFrom(type))
{
return true;
}
return type.GetAssignableTypes()
.Where(t => t.IsGenericType)
.Any(t=> t.GetGenericTypeDefinition() == parentType);
}
/// <summary>
/// Gets all parent types including the currrent type.
/// </summary>
public static IEnumerable<Type> GetAssignableTypes(this Type type)
{
if (type == null)
{
throw new ArgumentNullException(nameof(type));
}
// First check for interfaces because interface types don't have base classes.
foreach (Type iType in type.GetInterfaces())
{
yield return iType;
}
// Then check for base classes.
do
{
yield return type;
type = type.BaseType;
}
while (type != null);
}
Come up with better method names. Perhaps calling it IsCompatibleWith is misleading. Maybe IsKindOf ? Also, GetAssignableTypes can also be called GetParentTypes but that is also misleading. Naming is hard. Documenting it is better.
Some tests:
IsCompatibleWith(typeof(List<int>), typeof(IList<int>))
true
IsCompatibleWith(typeof(List<>), typeof(IList<>))
true
IsCompatibleWith(typeof(List<int>), typeof(IList<>))
true
IsCompatibleWith(typeof(List<int>), typeof(IList<string>))
false
I wrote a generic class and want to crate its instance from a static method. The problem is that I can’t create generic instance of the object. I know that it sounds confusing and it is better to show the code.
public class Parameter<T> : IParameter<T>
{
public string Name { get; set; }
public T Value { get; set; }
public bool IsValid()
{
if (String.IsNullOrEmpty(Name))
return false;
return (typeof(T) == typeof(String)) ||
typeof(T) == typeof(bool) ||
typeof(T) == typeof(int) ||
typeof(T) == typeof(double);
}
public XElement ToXml()
{
if (!IsValid())
throw new InvalidParameterException();
var xElement = new XElement("Parameter", Value,
new XAttribute("Type", typeof (T)),
new XAttribute("Name", Name));
return xElement;
}
public static Parameter<T> FromXml(XElement xElement)
{
var sType = xElement.Attributes()
.Where(attribute => attribute.Name == "Type")
.Single().Name.ToString();
var name = xElement.Attributes()
.Where(attribute => attribute.Name == "Name")
.Single().Name.ToString();
var sValue = xElement.Value;//need to use this
var typeVar = Type.GetType(sType);// and this to create proper instance of Parameter<T>
//I need somehow set T equal to typeVar here and Set
return new Parameter<T>() {Name = name};//this is wrong.
//I need return either Parameter<int> or Paramter<double> or Parameter<string> or Parameter<bool>
//basing on typeVar
}
}
I'm not sure if this possible at all... but looks like it is trivial object design requirement. Any ideas?
Thanks!
UPD: I'm using .NET 4.0. Does it make any difference? :)
UPD2: Looking at the problem now I see that this is a silly question. And it is impossible to return such "generic" objects.
Make a non-generic base class and inherit the generic class from it (they can have the same name and only differ by the generic type). On the non-generic base class, create generic instances in your static method (which returns the non-generic base class as result). You can then cast this to the generic type you expect.
public abstract class Parameter {
public static Parameter FromXml(XElement xElement) {
...
}
public string Name { get; set; }
public abstract XElement ToXml();
}
public class Parameter<T>: Parameter {
public T Value { get; set; }
public override XElement ToXml() {
...
}
}
There isn't really another way of doing this, since in your sample the type for T is specified before the static method runs.
The problem is: T is evaluated at compile time. The compiler does not have any chance to know, to which actual type your 'sType' will evaluate at runtime. Also, in the compiled assembly, no generics exist anymore. Therefore, in order to construct a type at runtime, based on condition which can only get evaluated at runtime, you will have to pesent the compiler a concrete type for compiling anyway. So somewhere you may decide your return type in an if .. else cascade like that:
if (sType is String)
return new Parameter<String>()
else if (sType is double)
return new Parameter<double>()
...
This may be placed inside a factory class or right near to the XElement class, I guess.
In order to be able to return Parameter for example, you may use an interface (or a common base class, like in another answer), which may stand for all Parameter variants. This is the reason, why the method, which parses the Xml IMO is better placed outside of Parameter.
Also, since it seems, you are cert of 'deserializing' from XML, consider using some de-/serializer functionality ;)
This does work for custom classes but it may not work for value types. Take a look at This Post to see how this work for heap types.
As Indicated by SLaks, this is impossible. Think of it this way,
Parameter<???> value = Parameter<???>.FromXml(...);
How will you ever resolve what the questionmarks should be when it depends on the content of the XmlElement?
You should use a common class which both captures Value as an object and exposes type information.
I'm having some trouble using reflection to differentiate between a non-generic and a generic method on a generic class. Here's a test case I'm working with:
public class Foo<T>
{
public string Bar( T value ) { return "Called Bar(T)"; }
public string Bar( int value ) { return "Called Bar(int)"; }
public static void CallBar<TR>(Foo<TR> foo)
{
var fooInfo = foo.GetType()
.GetMethods()
.Where(x => !x.IsGenericMethod && // doesn't filter out Bar(T)!
x.Name == "Bar" &&
x.GetParameters().First().ParameterType == typeof(int))
// !Two identical MethodInfo results, how to choose between them?
// Is there a gauranteed canonical ordering? Or is it undefined?
.First();
Console.WriteLine(fooInfo.Invoke(foo, new object[]{ 0 }));
}
}
// prints Bar(T)...
Foo<int>.CallBar( new Foo<int>() );
Unfortunately System.Reflection doesn't provide a good way to correlate a method on a constructed type with the corresponding method on the generic type definition from which it was constructed. There are two solutions I know of, neither one is perfect:
Solution #1: static TypeBuilder.GetMethod. There's a static version of GetMethod on TypeBuilder that accepts a generic constructed type and a MethodInfo for a method on a generic type definition, and returns the
corresponding method on the specified generic type. In this example, calling TypeBuilder.GetMethod(Foo<int>, Foo<T>.Bar(T)) will give you Foo<int>.Bar(T-as-int) which you can then use to disambiguate between it and Foo<int>.Bar(int).
(The above example will not compile, naturally; I've used Foo<int> and Foo<T>.Bar(T) to mean the respective Type and MethodInfo objects which, which are easily obtainable but would make the example too complex).
The bad news is that this only works when the generic type definition is a TypeBuilder, i.e. when you're emitting a generic type.
Solution #2: MetadataToken. It's a little known fact that type members retain their MetadataToken in the transition from generic type definitions to generic constructed types. So in your example, Foo<T>.Bar(T) and Foo<int>.Bar(T-as-int) should share the same MetadataToken. That would allow you to do this:
var barWithGenericParameterInfo = typeof(Foo<>).GetMethods()
.Where(mi => mi.Name == "Bar" &&
mi.GetParameters()[0].ParameterType.IsGenericParameter);
var mappedBarInfo = foo.GetType().GetMethods()
.Where(mi => mi.MetadataToken == genericBarInfo.MetadataToken);
(This will not compile either, unless I'm extremely lucky and managed to get it right the first time :) )
The problem with this solution is that MetadataToken wasn't meant for that (probably; the documentation is a little skimpy on that) and it feels like a dirty hack. Nevertheless, it works.
When using Foo<int>, the Bar(T) method is typed as Bar(int), making no distinction between it and the method with an int defined as the parameter.
To get the correct method definition of Bar(T), you can use typeof(Foo<>) instead of typeof(Foo<int>).
This will enable you to tell the difference between the two. Try the following code:
public static void CallBar<TR>(Foo<TR> foo)
{
Func<MethodInfo, bool> match = m => m.Name == "Bar";
Type fooType = typeof(Foo<>);
Console.WriteLine("{0}:", fooType);
MethodInfo[] methods = fooType.GetMethods().Where(match).ToArray();
foreach (MethodInfo mi in methods)
{
Console.WriteLine(mi);
}
Console.WriteLine();
fooType = foo.GetType();
Console.WriteLine("{0}:", fooType);
methods = fooType.GetMethods().Where(match).ToArray();
foreach (MethodInfo mi in methods)
{
Console.WriteLine(mi);
}
}
This will output:
System.String Bar(T)
System.String Bar(Int32)
System.String Bar(Int32)
System.String Bar(Int32)
Try looking at the generic type definition: typeof(Foo<>). The methods will be in the same order.
public class Foo<T> {
public string Bar(T value) { return "Called Bar(T)"; }
public string Bar(int value) { return "Called Bar(int)"; }
public static void CallBar<TR>(Foo<TR> foo) {
var footinfo = typeof(Foo<>).GetMethods();
int i;
for (i = 0; i < footinfo.Count(); ++i) {
if (footinfo[i].Name == "Bar" && footinfo[i].GetParameters()[0].ParameterType.IsGenericParameter == false)
break;
}
Console.WriteLine(foo.GetType().GetMethods()[i].Invoke(foo, new object[] { 0 }));
}
}
// prints Bar(int)...
Foo<int>.CallBar( new Foo<int>() );
The ContainsGenericParameters property is true for both Bar's in Foo<> and false for both Bar's in Foo, so its useless.
I think ContainsGenericParameters is what you're looking for, according to the documentation:
http://msdn.microsoft.com/en-us/library/system.reflection.methodinfo.isgenericmethod.aspx
http://msdn.microsoft.com/en-us/library/system.reflection.methodinfo.containsgenericparameters.aspx
As Eric Lippert points out, neither of them are generic methods; your class is generic, but you're passing a non-generic instance of the class. Therefore the methods aren't generic the way reflection sees it.
You should be on the right track if you change
foo.GetType()
to
foo.GetGenericTypeDefinition()
For more info, see MSDN's documentation.