Rémi
Rémi

Reputation: 3967

Downcast an inherited class to base class

Let say i have a base class

class baseClass
{  }

And another class that inherit from that baseClass

class foo : baseClass
{  }

I tryed to cast it back directly (baseClass)foo but the compiler say it cannot be done.

Is there a way from foo to get only the baseClass?

Upvotes: 0

Views: 183

Answers (4)

Devolus
Devolus

Reputation: 22084

If you derive a class A from class B you can always refer to A as if it were B. Of course this is not true in the revese case. In general you can always refer down the chain of inherited classes.

Upvotes: 2

2GDev
2GDev

Reputation: 2466

Here a working example with different Namespaces

namespace BaseNameSpace
{
    public class BaseClass
    {
        public string Name { get; set; }
    }
}

namespace TestNameSpace.Class
{

    public class TestClass : BaseClass
    {
        public string Address { get; set; }
    }
}

Use :

TestClass test1  = new TestClass();
BaseClass b = test1;

Ensure that there is the correct using :

using BaseNameSpace;
using TestNameSpace.Class;

Upvotes: 0

Serge
Serge

Reputation: 6692

If the compiler complain on such a thing, it could just mean you have several baseClass defined in several Namespace and you're actually not referencing the right baseClass.

Check your Namespaces it should solve your bug.

Upvotes: 1

Sergey Berezovskiy
Sergey Berezovskiy

Reputation: 236218

foo is a baseClass you don't need any casting. And your code should work without any problems:

var foo = new foo();
baseClass x = (baseClass) foo;

Upvotes: 5

Related Questions