RastaBaby
RastaBaby

Reputation: 71

Casting to Generic base class failing

I am failing to see why my attempt to cast to a generic base class is not working.

The basic structure of the code is as follows.

interface ICmd
{
}

class Context
{
}

class Cmd<TContext> : ICmd
    where TContext : Context
{
}

class MyContext : Context
{
}

class MyCmd : Cmd<MyContext>
{
}

So now I have an instance of ICmd and want to cast it to Cmd as follows

var base = cmd as Cmd<Context>

base is always null after this line is executed.

changing cast to be specific for the context only and it works.

var base = cmd as Cmd<MyContext>       -- this works ???

Hope I have provided enough information, is this a covariance\contravariance issue?

Thanks

Upvotes: 7

Views: 11547

Answers (2)

Daniel Hilgarth
Daniel Hilgarth

Reputation: 174289

You may want to use co- and contravariance.

The problem is that Cmd<Context> is not the base class of Cmd<MyContext>.

See this recent question for a more detailed answer: C# Generics Inheritance Problem

Upvotes: 10

Yannick Motton
Yannick Motton

Reputation: 35971

What you need here is covariance. C# 4 currently does not allow variance for generic type parameters in classes. If your interface doesn't need to allow using the TContext in any input positions, you can consider making the interface generic, and covariant in TContext:

interface ICmd<out TContext> where TContext : Context { }

class Cmd<TContext> : ICmd<TContext> where TContext : Context { }

static void Main(string[] args)
{
    Cmd<MyContext> cmd = new Cmd<MyContext>();

    var foo = cmd as ICmd<Context>;
}

Upvotes: 2

Related Questions