Take the 2-minute tour ×

I want to create a set of classes that are very similar and can be cast to each other types. My idea was that I would create an Interface object and implement it through a base class. Then create additional classes that inherit from my base. I could then use the Interface to work with the common (base) methods and cast an object from the BASE object to a custom type.

interface ImyInterface {


public class MyBase : ImyInterface {


public class MyCustom1 : MyBase {


public class MyCustom2 : MyBase {


// in helper class
public static MyBase GetGeneralOjbect() {

    // get a generic base object
    return new MyBase();

// How I'm trying to use this

MyCustom1 obj = GetGeneralOjbect() as MyCustom1;

This seems to work except for the casting of the object statement. MyCustom1 is always null even though the static helper GetGeneralOjbect returns a good MyBase object. Maybe this can't be done or I'm not doing it correctly. Any input would be appreciated.

share|improve this question

5 Answers 5

up vote 3 down vote accepted

This is because you can cast a MyCustom1 or MyCustom2 to MyBase, but not necessarily the other way.

When you create a MyBase via MyBase b = new MyBase();, b is a MyBase but not a MyCustom2, so casting b to MyCustom2 will fail.

What you can do is:

MyBase b = new MyCustom2();
MyCustom2 c = b as MyCustom2();

What you can't do is:

MyBase b = new MyCustom2();
MyCustom1 c = b as MyCustom1();
share|improve this answer
I suspected this was the case. Thought I would try it out for this particular situation I was doing but wasn't sure if it was correct. Thanks for your input. –  Darren - Apr 4 '12 at 14:43
Well...you can do it...it will just crash and burn at runtime. MyCustom1 c = new MyCustom2(); won't even compile, even with an explicit cast. –  Servy Apr 4 '12 at 14:47
Yes, you can do it, but as the OP noticed, the result of the second cast will be null. –  Thorsten Dittmar Apr 4 '12 at 15:07

The "as" keyword says "if this object which is statically typed as MyBase has a runtime type of MyCustom1, then give it back to me statically typed as MyCustom1; otherwise, give me a null reference". The object you are casting has a runtime type of MyBase, not MyCustom1, which is why you are getting a null reference.

share|improve this answer

Basically you can cast up an inheritance chain but not down it. Say you had the following class heirarchy:

public class A {

public class B : A {

public class C : B {

If you instantiated a new instance of type B you could cast it to A but not C.

share|improve this answer

Have you considered using Factory Pattern?

share|improve this answer

An instance of MyCustom1 can be used whenever an instance of MyBase is expected, but MyBase cannot be used when MyCustom1 is expected.

share|improve this answer

Your Answer


