Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What actually happens when I perform a downcast?

How exactly does this work?

If I have this base class

public class BaseClass
{
    public int Value1 { get; set; }
    public int Value2 { get; set; }

    public BaseClass SimpleClone()
    {
        BaseClass result = new BaseClass();
        result.Value1 = this.Value1;
        result.Value2 = this.Value2;
        return result;
    }
}

And this child class

public class DerivedClass : BaseClass
{
    public bool Value3 { get; set; }

    public DerivedClass()
    {
        Value3 = true;
    }
}

How can I downcast BaseCast.SimpleClone() into anotherObj? What would happen to Value3? While knowing what happens is good, I am also interested in why it works this way.

like image 236
Kyle Baran Avatar asked Dec 25 '22 09:12

Kyle Baran


1 Answers

If I understand correctly your question is What happens when you do the following

DerivedClass derived = (DerivedClass)baseObj.SimpleClone();

Did you try that? Simply it will result in InvalidCastException since BaseClass is not DerivedClass.

I have answered a similar question here, That should clear things up.

like image 181
Sriram Sakthivel Avatar answered Jan 05 '23 06:01

Sriram Sakthivel