Brandon Moore
Brandon Moore

Reputation: 8780

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.

Upvotes: 13

Views: 13149

Answers (3)

roken
roken

Reputation: 3994

The reason you can't reference the static member like this:

O.MyStaticMethod(); 

Is because you don't know what type O is. Yes, it inherits from BusinessObject, but static members are not inherited between types, so you can only reference MyStaticMethod from BusinessObject.

Upvotes: 4

ose
ose

Reputation: 4075

If you are forcing O to inherit from BusinessObject, why not just call it like this:

void SomeMethod()
{
    var s = BusinessObject.MyStaticMethod(); // <- How to do this?
}

Upvotes: 2

JaredPar
JaredPar

Reputation: 754763

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.

Upvotes: 14

Related Questions