Fun with casting and inheritance

Posted by Vaccano on Stack Overflow See other posts from Stack Overflow or by Vaccano
Published on 2010-05-25T21:19:59Z Indexed on 2010/05/25 21:31 UTC
Read the original article Hit count: 247

Filed under:
|
|
|
|

NOTE: This question is written in a C# like pseudo code, but I am really going to ask which languages have a solution. Please don't get hung up on syntax.

Say I have two classes:

 class AngleLabel: CustomLabel
 {
     public bool Bold;
     // code to allow the label to be on an angle
 }

 class Label: CustomLabel
 {
     public bool Bold;
     // Code for a normal label
     // Maybe has code not in an AngleLabel (align for example).
 }

They both decend from this class:

 class CustomLabel: Control
 {
     protected bool Bold;
 }

The bold field is exposed as public in the descended classes.

No interfaces are available on the classes.

Now, I have a method that I want to beable to pass in a CustomLabel and set the Bold property. Can this be done without having to 1) find out what the real class of the object is and 2) cast to that object and then 3) make seperate code for each variable of each label type to set bold. Kind of like this:

 public void SetBold(customLabel: CustomLabel)
 {
     AngleLabel angleLabel;
     NormalLabel normalLabel;


     if (angleLabel is AngleLabel )
     {
        angleLabel= customLabel as AngleLabel 
        angleLabel.Bold = true;
     }

     if (label is Label)
     {
        normalLabel = customLabel as Label
        normalLabel .Bold = true;
     }
 }

It would be nice to maybe make one cast and and then set bold on one variable.

What I was musing about was to make a fourth class that just exposes the bold variable and cast my custom label to that class.

Would that work?

If so, which languages would it work for? (This example is drawn from an old version of Delphi (Delphi 5)). I don't know if it would work for that language, (I still need to try it out) but I am curious if it would work for C++, C# or Java.

If not, any ideas on what would work? (Remember no interfaces are provided and I can not modify the classes.)

Any one have a guess?

© Stack Overflow or respective owner

Related posts about c#

Related posts about c++