Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

downcasting to which object

Tags:

c#

.net

Following code is executed:

ClassA myClass = new ClassA()
myClass.varA = "Teststring"

BaseClassB cls = new BaseClassB()
cls.methodA(myClass)

I have following classes

class BaseClassA
{

}

class ClassA:BaseClass
{
   string varA;
}

class ClassB:BaseClass
{
   string varB;
}

Then one method

class BaseClassB
{
   public void methodA(BaseClassA myVar)
   {
      // How can I display varA that is given with myClass (which is myVar)?
      // It should also be able to display varB when an object of type ClassB is given
      // So I have to make a downcast here but I don't know if I have to downcast to ClassA or ClassB
   }
}

I know this is main knowledge but can somebody help me?

like image 335
Ozkan Avatar asked Jul 19 '26 07:07

Ozkan


2 Answers

You are probably wanting to restructure your code rather than putting code in where you have indicated. The whole point of base classes is that you can treat ClassA and ClassB the same. If you want to treat them differently then have overloads that take ClassA and ClassB objects...

class BaseClassB
{
    public void methodA(ClassB myVar)
    {
        Console.WriteLine(myVar.varB);
        methodCommon(myVar);
    }
    public void methodA(ClassA myVar)
    {
        Console.WriteLine(myVar.varA);
        methodCommon(myVar);
    }
    public void methodCommon(BaseClassA myVar)
    {
    }
}

if you really need it in one method then you can do:

public void methodA(BaseClassA myVar)
{
    if (myVar is ClassA)
    {
        //Its of type ClassA so you can do whatever you want with it knowing it is a ClassA.
    }
    else if (myVar is ClassB)
    {
        //Its of type ClassB so you can do whatever you want with it knowing it is a ClassB.
    }
    else
    {
        //Its not either.
    }
}
like image 181
Chris Avatar answered Jul 20 '26 20:07

Chris


If you are sure that myVar is either ClassA or ClassB, you can do this:

string s;
var myvarA = myVar as ClassA;
if (myvarA != null)
{
    s = mayVarA.varA;
}
else
{
    s = ((myvarB)myVar).varB;
}

If myVar can be something else, you can do the same test than for ClassA for ClassB to be sure.

like image 37
Falanwe Avatar answered Jul 20 '26 21:07

Falanwe