Casting to Generic base class failing

10,440

Solution 1

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

Solution 2

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>;
}
Share:
10,440
RastaBaby
Author by

RastaBaby

Updated on August 08, 2022

Comments

  • RastaBaby
    RastaBaby almost 2 years

    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