stackedAE
stackedAE

Reputation: 303

Implementing a generic interface for any type in a concrete class in C#

I want to do something like the following

    public abstract class StaticValue : IRefDynamicValue<RefT>
    {
        public abstract int get();

        public int get(RefT refValue)
        {
            return get();
        }
    }

    public interface IRefDynamicValue<RefT> 
    {
        public int get(RefT refValue);
    }

In my specific case, I'm making a game where I have IRefDynamicValue<Actor>, IRefDynamicValue<Ability>, etc., but I want StaticValue (basically just an int) to be able to serve as any of them (for example an ability parameter).

In general though, the situation is that I have a concrete type that I want to be able to implement a generic interface for any type because it just ignores and never uses the type parameter.

The code above of course isn't possible in C#. Is there a different way to implement this kind of relationship in C#, either through some other trick with generics or just an alternate code structure?

Upvotes: 2

Views: 498

Answers (2)

Enigmativity
Enigmativity

Reputation: 117175

It seems to me that you need this:

public abstract class StaticValue : IRefDynamicValue
{
    public abstract int get();

    public int get<RefT>(RefT refValue)
    {
        return get();
    }
}

public interface IRefDynamicValue
{
    public int get<RefT>(RefT refValue);
}

Upvotes: 0

Sweeper
Sweeper

Reputation: 274770

Implement IRefDynamicValue<object>, and make IRefDynamicValue contravariant:

public abstract class StaticValue : IRefDynamicValue<object>

// and also:
public interface IRefDynamicValue<in RefT> 

Now you can do:

IRefDynamicValue<Actor> x = someStaticValue;

Note that this doesn't work for RefTs that are value types.

Upvotes: 3

Related Questions