Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Generic question... Calling a static method from a generic class

I have a generic class:

public class MyList<LinkedItem> : List<LinkedItem> where LinkedItem : MyItem, new()
{
}

From that generic class, I would like to access a static function from the LinkedItem Class which is a descendant of MyItem class. (thus without creating an instance of the LinkedItem).

Is it possible?

Thank you,

Eric

like image 715
Eric Avatar asked Mar 01 '26 15:03

Eric


1 Answers

Yes, it is possible, but you have to use reflection by obtaining a MethodInfo from typeof(T).GetMethod("Foo", BindingFlags.Public | BindingFlags.Static) and then calling Invoke on it.

It can be very useful, particularly if using the same technique on a ConstructorInfo rather than a MethodInfo, to create a generic factory that uses parameters in the constructor. It is though one to use sparingly. In particular, there is no way of guaranteeing at compile time that the type in question has a static method of the required signature, so type-safety is gone and such an error won't be caught until run-time.

like image 183
Jon Hanna Avatar answered Mar 04 '26 04:03

Jon Hanna