MalcomTucker
MalcomTucker

Reputation: 7477

Cannot convert type to instance of interface in generic method with type constraint?

Why does this give me a compile time error Cannot convert 'ListCompetitions' to 'TOperation':

public class ListCompetitions : IOperation
{
}

public TOperation GetOperation<TOperation>() where TOperation : IOperation
{
    return (TOperation)new ListCompetitions(); 
}

Yet this is perfectly legal:

public TOperation GetOperation<TOperation>() where TOperation : IOperation
{
    return (TOperation)(IOperation)new ListCompetitions(); 
}

Upvotes: 0

Views: 869

Answers (2)

Daniel Imms
Daniel Imms

Reputation: 50229

Because TOperation could be anything that implements IOperation, you can't be sure that ListCompetitions is a TOperation.

You probably want to be returning an IOperation:

public IOperation GetOperation<TOperation>() where TOperation : IOperation
{
    return new ListCompetitions(); 
}

Upvotes: 1

Lee
Lee

Reputation: 144206

This cast is not safe since you could supply a generic argument different from ListCompetitions for TOperation, for example you could have:

public class OtherOperation : IOperation { }
OtherOperation op = GetOperation<OtherOperation>();

If the compiler allowed your method, this would fail at runtime.

You could add a new constraint e.g.

public TOperation GetOperation<TOperation>() where TOperation : IOperation, new()
{
    return new TOperation();
}

alternatively you could change the return type to IOperation:

public IOperation GetOperation()
{
    return new ListCompetitions();
}

It's not clear what the benefit of using generics is in this case from your example.

Upvotes: 4

Related Questions