Ts there any way to call a static member on type when I only have a generic parameter. For example if I have something like this
public Get<T>(int id)
{
// I would like to do this
string s = T.SomeMethodName();
}
I could do it like this but is kinda “yucky”, and then it does not matter if it is static or not. Or I could use reflection as suggested by Yuriy.
ISomeKnownInterface i = (ISomeKnownInterface ) new T();
string s = i.SomeMethodName();
So question is now which is better approach, creating new instance of using reflection
public TFormDto Get<TFormDto>(int entityId) where TFormDto : AbstractEntityFormDto, new()
{
// create new instance
AbstractEntityFormDto a = (AbstractEntityFormDto) new TFormDto();
string entityName = a.GetEntityFullTypeName();
// use reflection
Type type = typeof(TFormDto);
string entityName = type.GetMethods(BindingFlags.Public | BindingFlags.Static)
.Single(m => m.Name == "GetEntityFullTypeName")
.Invoke(null, null);
Wouldn’t that just always be AbstractBaseClass.GetFullName(). Otherwise you have to use reflection on T to get the static method of another class. This might be helpful.
The following is a simple example:
With your sample, I assume you know interfaces don’t have static methods. I assumed you meant you had an interface which has a signature for the static method and a class implementing said interface would just call the static method from the implementation. That would work as well, but you’re not guaranteed the correct static will be called and make sure T has a constraint on that interface, not just new().