Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to access static methods of generic types

public class BusinessObjects<O>
    where O : BusinessObject
{
    void SomeMethod()
    {
        var s = O.MyStaticMethod(); // <- How to do this?
    }
}

public class BusinessObject
{
    public static string MyStaticMethod()
    {
        return "blah";
    }
}

Is there a correct object oriented approach to accomplishing this or will I need to resort to reflection?

EDIT: I went too far in trying to oversimplify this for the question and left out an important point. MyStaticMethod uses reflection and needs the derived type to return the correct results. However, I just realized another flaw in my design which is that I can't have a static virtual method and I think that's what I would need.

Looks like I need to find another approach to this problem altogether.

like image 745
Brandon Moore Avatar asked Feb 05 '12 02:02

Brandon Moore


1 Answers

You can't access a static method through a generic type parameter even if it's constrained to a type. Just use the constrained class directly

var s = BusinessObject.MyStaticMethod();

Note: If you're looking to call the static method based on the instantiated type of O that's not possible without reflection. Generics in .Net statically bind to methods at compile time (unlike say C++ which binds at instantiation time). Since there is no way to bind statically to a static method on the instantiated type, this is just not possible. Virtual methods are a bit different because you can statically bind to a virtual method and then let dynamic dispatch call the correct method on the instantiated type.

like image 135
JaredPar Avatar answered Sep 28 '22 03:09

JaredPar