0

I have a class that have a type parameter that I would like to assign to a more generic type parameter:

public StrategyContext<T> : where T : IStrategy {}

StrategyContext is a class to help designing unit test. Using xUnit and the Theroy attribute I can assert some common behavior to all my strategy. For example:

[Theory]
[InlineData(typeof(LeftStrategy))]
[InlineData(typeof(RightStrategy))]
public void HasAName(Type contextType)
{
    Type strategy = typeof(StrategyContext<>);
    var context = (StrategyContext<IStrategy>)Activator.CreateInstance(strategy.MakeGenericType(contextType));
}

Unfortunatly the runtime can not convert from a StrategyContext<LeftStrategy> to StrategyContext<IStrategy>

So I thought that covariance is what I needed but it is not possible to declare the class as:

public StrategyContext<out T> : where T : IStrategy {}

Any other solution?

mathk
  • 7,973
  • 6
  • 45
  • 74

0 Answers0