1

I have two classes, where the first class references the second class. My question is, why in the second class, the line cl.container = this as ClassContainer<MyClass>; does work and the explicit cast cl.container = (ClassContainer<MyClass>)this; does not.

class MyClass
{
    public ClassContainer<MyClass> container { get; set; }
}

second class:

class ClassContainer<T> where T : MyClass
{
    public ClassContainer()
    {
        MyClass cl = new MyClass();
        cl.container = this as ClassContainer<MyClass>; // works
        cl.container = (ClassContainer<MyClass>)this;   // does not work
    }
}
wake-0
  • 3,918
  • 5
  • 28
  • 45

1 Answers1

1

This is because as is a safe cast, i.e. it will not raise an exception or a compiler error if the type can not be casted. It will simply return null. c1.container should be null after using as.

From your code, you may be trying to use variant generics. Check out this link at MSDN to help achieve what you were trying to do. You'll have to use interfaces though, and cannot make a type parameter both covariant and contravariant.

Community
  • 1
  • 1
EvilTak
  • 7,091
  • 27
  • 36