Search code examples
c#castingdowncast

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.


Solution

  • The question as it stands does not make sense. There is no possibility for downcasting, because your clone method already returns the base class. What I think you do (should) want here is override the clone method in your subclass:

    public class DerivedClass : BaseClass
    {
        //... Other stuff
        public BaseClass SimpleClone()
        {
            var result = new DerivedClass 
                             {
                                 Value1 = this.Value1,
                                 Value2 = this.Value2,
                                 Value3 = this.Value3,
                             }
            return result;
        }
    

    Now, if you have an object of type DerivedClass and call clone on it, the compiler does not know that the returned object is of type DerivedClass, because of the method signature. But you do, so in that case you can cast the object. All it does is tell the compiler: 'I know better, you think this is a BaseClass but it actually is a DerivedClass'. It has no runtime impact because you don't change the type of the object, you only provide the compiler with extra information.