cast base class to derived class

SiamIT

Well-known member
Joined
Aug 3, 2021
Messages
53
Programming Experience
5-10
Greetings,
I am in a need to extend a class to add few new methods/properties that base class lacks.
so, i have created a class that extend another class. but issue arises when i need to covert/cast base class to derived class. it doesn't works.
so? is i am doing it wrong, or it's not possible to cast directly? if so then what is the alternative way.. because i need the cast to have the new methods to base class.

this is just a sample code for testing (for this thread/post), actual class is little bigger/complex than this.. but the principle/issue is same..

C#:
    public class LabelEx : System.Windows.Forms.Label
    {
        public LabelEx TestCast()
        {
            System.Windows.Forms.Label label = new System.Windows.Forms.Label();
            //return label; //this doesn't even compile
            return (LabelEx)label; //this complies but on execution it throws error
        }
    }

so? how can i do this? please?

best regards
 
You can't. If you have a Label object then it can't just become a LabelEx object. Casting doesn't change anything about the object itself; it only changes the type of the reference via which you access the object. The object must already be the type you're casting as. As for a conversion, it doesn't affect the existing object either. It creates a new object of the specified type whose contents is based on the existing object. For example, you can convert any object to a string by calling its ToString method but that creates a new string based on the existing object while the existing object itself is unaffected. You could declare a copy constructor in your LabelEx class that copied all the properties from the existing Label but that wouldn't help you, because any changes you made to that object would not affect the original Label.

The thing is though, why would you even need to cast or convert anything? If you want a control that IS a Label but has some extra properties, simply define a class that inherits Label and adds those properties, then use that class INSTEAD OF standard Labels. You can simply add instances of that class to your form instead of standard Label controls and then you have a control that acts exactly like a Label (because it IS a Label, because that's how inheritance works) but also has the extra properties. There's no casting or conversion required. You simply use your derived type everywhere. Note that, when you define a type that inherits Control and then build your project, that type will appear at the top of the Toolbox within the current solution, so you can use it like you would any other control.
 
You can't. If you have a Label ........ control.

first of all thanks a lot for taking that much time to write down that long response. I am so amazed.

but issue, is as i have told, my inheritance class is bit complex. thus few methods needs to have the cast/convert in place and it's necessary ( i am sorry, but i don't know whether is there any other way around).

let me give you the actual example, thus you will better understand..

C#:
    public class JsonObjectEx : Chilkat.JsonObject
    {
        /*
        here quite a few properties and methods exists which extend the base class Chilkat.JsonObject
        which is not part of this issue, so to make the post smaller, i truncated this....
        */

        //as you know JSON is a deep level object, that means a JSON object can have child JSON object and also that child JSON object can have ... so on..
        //so we need to get the child object, this not the main/base object, but child object of base object
        //and it returns an Chilkat.JsonObject that needs to be converted/cast to JsonObjectEx to have to access to extended methods/properties of JsonObjectEx
        public new JsonObjectEx ObjectOf(string jsonPath)
        {
            return (JsonObjectEx)base.ObjectOf(jsonPath);
        }

        //same here, we need to add JSON object at a child level.. not at parent/base level.. 
        //and it returns an Chilkat.JsonObject that needs to be converted/cast to JsonObjectEx to have to access to extended methods/properties of JsonObjectEx
        public new JsonObjectEx AppendObject(string name)
        {
            return base.AppendObject(name) as JsonObjectEx;
        }
    }

i hope this makes the cloud little more clear?


once again, sorry for my bad English and also thanks again for your kind and brought reply
 
As I said in the first place, you can't do that. You cannot cast an object as a type it isn't. If you're not a native English speaker then you may not have heard the expression "to cast something in a different light". That is the meaning "cast" has when used in programming. Casting something in a different light literally means to shine light on it from a different angle and thereby make aspects of it visible that weren't previously. The object doesn't change but how you view it does. The same is true when casting in programming. The object doesn't change but, by casting as a different type, you can access members of that object that were previously inaccessible.

In your case, for the first method at least and possibly for the second too, the base method you're calling is returning a new object that is type JsonObject, so you can't just make it become a different type out of thin air. What you could do is add a copy constructor to your derived class that accepted an object of the base type and returned an object of the derived type with all the property values copied across. That would work as long as it's not important that you actually access the original object created.
 
As I said in the first place, you can't do that. You cannot cast an object as a type it isn't. If you're not a native English speaker then you may not have heard the expression "to cast something in a different light". That is the meaning "cast" has when used in programming. Casting something in a different light literally means to shine light on it from a different angle and thereby make aspects of it visible that weren't previously. The object doesn't change but how you view it does. The same is true when casting in programming. The object doesn't change but, by casting as a different type, you can access members of that object that were previously inaccessible.

In your case, for the first method at least and possibly for the second too, the base method you're calling is returning a new object that is type JsonObject, so you can't just make it become a different type out of thin air. What you could do is add a copy constructor to your derived class that accepted an object of the base type and returned an object of the derived type with all the property values copied across. That would work as long as it's not important that you actually access the original object created.

thanks a lot again for your kind response, is there any sample you can provide (or even any link) to use copy constructor?

best regards
 
It's exactly what it sounds like: a constructor that copies properties and possibly fields from an existing base type object to the new derived type object.
C#:
public class BaseClass
{
    public string BaseProperty { get; set; }

    // ...
}

public class DerivedClass : BaseClass
{
    public string DerivedProperty { get; set; }

    public DerivedClass(BaseClass baseClass)
    {
        BaseProperty = baseClass.BaseProperty;
        // ...
    }
}
C#:
var bc = new BaseClass();

bc.BaseProperty = "Hello World";

var dc = new DerivedClass(bc);

Console.WriteLine(dc.BaseProperty);
You can make it private if it's only used internally. It's also worth noting that, because it's inside the derived class, you have access to protected members of the base class, so you can copy protected fields.
 
Back
Top Bottom