Skip to content

Instantly share code, notes, and snippets.

@kazyx
Last active January 28, 2017 04:00
Show Gist options
  • Save kazyx/9cdc033dd3bf19724b5253c759705a8f to your computer and use it in GitHub Desktop.
Save kazyx/9cdc033dd3bf19724b5253c759705a8f to your computer and use it in GitHub Desktop.
How to detect Type of generic property, in other words generic argument, from derived class
public class Main {
public Type GetTypeOfGenericArg(Type derivedClassType) {
var typedMyInterfaceType = derivedClassType.GetInterface(typeof(MyInterface<>).FullName);
// If derivedClassType is 'MyFoo', typedMyInterfaceType is typeof(MyInterface<Foo>)
return typedMyInterfaceType.GetGenericArguments()[0];
}
public Type GetTypeOfGenericArgByPropertyName(Type derivedClassType) {
var myParamPropertyInfo = derivedClassType.GetProperty(nameof(MyInterface.MyParameter));
// If derivedClassType is 'MyFoo', myParamPropertyInfo is PropertyInfo of MyFoo.MyParameter
return myParamPropertyInfo.PropertyType;
}
}
public interface MyInterface<T> {
T MyParameter { set; get; }
}
public class Foo {
public string Bar { set; get; }
}
public class MyFoo : MyInterface<Foo> {
public Foo MyParameter { set; get; }
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment