Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# inheritance casting one child to another

I have this simple structure: 1 parent, and two different childs.

public class Parent{}

public class ChildA : Parent{}

public class ChildB : Parent{}

I have an object objA of type ChildA, which I want to cast to ChildB. My naive approach says:

ChildA objA = new ChildA();

ChildB objB = (ChildB)objA;

But this is not directly possible - why? Is this because I need to implement some functions or because my naive approach is wrong?

Regards, Casper

like image 226
Chau Avatar asked Dec 04 '09 11:12

Chau


People also ask

What C is used for?

C programming language is a machine-independent programming language that is mainly used to create many types of applications and operating systems such as Windows, and other complicated programs such as the Oracle database, Git, Python interpreter, and games and is considered a programming foundation in the process of ...

What is the full name of C?

In the real sense it has no meaning or full form. It was developed by Dennis Ritchie and Ken Thompson at AT&T bell Lab. First, they used to call it as B language then later they made some improvement into it and renamed it as C and its superscript as C++ which was invented by Dr.

Is C language easy?

Compared to other languages—like Java, PHP, or C#—C is a relatively simple language to learn for anyone just starting to learn computer programming because of its limited number of keywords.

What is C language?

C is an imperative procedural language supporting structured programming, lexical variable scope, and recursion, with a static type system. It was designed to be compiled to provide low-level access to memory and language constructs that map efficiently to machine instructions, all with minimal runtime support.


2 Answers

It's not possible because the object objA refers to is not a ChildB. To put it another way, here's an example of what you're trying to do:

 string x = "hi";
 FileStream y = (FileStream) x;

They both have a common parent - System.Object - but they're completely different classes. What would you expect to happen if you tried to read from y?

Suppose your ChildB type has some field which is specific to that type - what would you expect that field's value to be after casting objA?

Why do you want to pretend that a ChildA is actually a ChildB? Could you maybe add a method in the parent class which does what you want? Add a method in ChildA like this:

ChildB ToChildB()

to perform an appropriate conversion?

like image 138
Jon Skeet Avatar answered Oct 01 '22 01:10

Jon Skeet


It is not possible to simply cast one object other type even if thay have one parent, because thay maybe have different interfaces.

You need to implement explicit or implitic operator of ChildA (or ChildB).

class ClassA
{
    public string Property1 { get; set; }
}

class ClassB
{
    public string Property2 { get; set; }

    public static implicit operator ClassB(ClassA classA)
    {
        return new ClassB() { Property2 = classA.Property1 };
    }
}

or

class ClassA
{       {
    public string Property1 { get; set; }

    public static explicit operator ClassB(ClassA classA)
    {
        return new ClassB() { Property2 = classA.Property1 };
    }
}

class ClassB
{
    public string Property2 { get; set; }
}

And after implementing conversings operators following code will work fine:

var a = new ClassA() {Property1 = "test"};
ClassB b = (ClassB)a;
Console.WriteLine(b.Property2); // output is "test"

In first case you can omit explicitely type conversion and write just like this:

var a = new ClassA() {Property1 = "test"};
ClassB b = a;

And finally if you want to synchronize only properties of parent class you can write converter directly in parent:

class Parent
{
    public string ParentProperty { get; set; }
    public static T1 Convert<T1>(Parent obj) where T1 : Parent, new()   
    {
    var result = new T1();
    result.ParentProperty = obj.ParentProperty;
    return result;
    }
}

Using (ClassA and ClassB childs of Parent):

var a = new ClassA();
a.ParentProperty = "test";
ClassB b = Parent.Convert<ClassB>(a);
Console.WriteLine(b.ParentProperty); // output is "test"
like image 44
bniwredyc Avatar answered Oct 01 '22 01:10

bniwredyc