Miyamoto Musashi
Miyamoto Musashi

Reputation: 31

How do I call static method for a generic type in a class?

interface TerminationCondition
{
    static bool IsSatisfied(some parameters);
}

Let's say some classes A and B implement this interface.

Some other class C has a generic type:

class C<termCondition> where termCondition : TerminationCondition

I need to call IsSatisfied from C accordingly, whether I have passed A or B for the generic type. For some reason it is not possible termCondition.IsSatisfied().

To summarize, the question is How do I call static method for a generic type in a class?

Upvotes: 2

Views: 140

Answers (3)

TrueWill
TrueWill

Reputation: 25523

bool result = C<TerminationCondition>.IsSatisfied();

As @SLaks pointed out, you can't have static methods in an interface. Having them in a generic type tends to be awkward.

@Austin also makes a good point.

You can have static generic methods (normally in non-generic types); these have their uses.

public static bool IsSatisfied<T>(T condition)
    where T: TerminationCondition

Upvotes: 1

Austin Salonen
Austin Salonen

Reputation: 50215

Since termCondition is required to be of type TerminationCondition, you could simple have IsSatisfied be an instance method of the classes that implement that interface. There's no need to have that method be static at all.

Upvotes: 2

SLaks
SLaks

Reputation: 887375

This is not possible.

In fact, you can't have static methods in an interface at all.

Upvotes: 6

Related Questions