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?
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.
}
}
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With