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

Time:07-13

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 serve implement a generic interface because it just ignores and never uses 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?

CodePudding user response:

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.

  • Related