Vee
Vee

Reputation: 73

generic type interface cast to a specific interface

How can you cast an interface with a generic type to a common interface?

Lets say we have the following interfaces/objects:

public interface IAction : IAction<object> { }
public interface IAction<T>
{
    T PerformAction();
}
public class SomeAction : IAction<string>
{
    public string PerformAction()
    {
        return "some action result value";
    }
}
public class OtherAction : IAction<int>
{
    public int PerformAction()
    {
        return 100;
    }
}

Then if we try to code it in a console application:

List<IAction> actions = new List<IAction>();
actions.Add(new SomeAction());
actions.Add(new OtherAction());
actions.ForEach(e => Console.WriteLine(e.PerformAction()));

How can we work around the error "cannot convert from 'SomeAction' to 'IAction'"?

Upvotes: 0

Views: 64

Answers (1)

Igor
Igor

Reputation: 62298

Your inheritance hierarchy does not make sense, you should have IAction<T> extend IAction and not the other way around.

You also need to add any common methods you want to call to IAction and, if the methods have the same name and parameters, implement them using an explicit interface implementation. It is on the common interface implementation you will be calling the method.

public interface IAction
{
    object PerformAction();
}
public interface IAction<T> : IAction
{
    new T PerformAction();
}
public class SomeAction : IAction<string>
{
    object IAction.PerformAction()
    {
        return PerformAction();
    }

    public string PerformAction()
    {
        return "some action result value";
    }
}
public class OtherAction : IAction<int>
{
    object IAction.PerformAction()
    {
        return PerformAction();
    }
    public int PerformAction()
    {
        return 100;
    }
}

Calling code

List<IAction> actions = new List<IAction>();
actions.Add(new SomeAction());
actions.Add(new OtherAction());
actions.ForEach(e => Console.WriteLine(e.PerformAction()));

Upvotes: 2

Related Questions