G
Guest
Is there any way to cast a base class object to a derived class datatype when
the derived class adds no new fields nor alters the object allocation in any
way?
The scenario would be where you want to extend a base class by adding only
methods and properties, however, only base class objects are provided to you.
Here is a sample:
public class Base
{
protected int val = 0;
}
public class Derived : Base
{
public int GetVal()
{
return val;
}
}
Then using those classes in a function like this:
public int Fn( Base a )
{
Derived b = (Derived)a;
return b.GetVal();
}
Assuming allocation doesn't change, there should be no harm in doing a cast
like this. Are there class modifiers that could handle this?
Thanks, Chris.
the derived class adds no new fields nor alters the object allocation in any
way?
The scenario would be where you want to extend a base class by adding only
methods and properties, however, only base class objects are provided to you.
Here is a sample:
public class Base
{
protected int val = 0;
}
public class Derived : Base
{
public int GetVal()
{
return val;
}
}
Then using those classes in a function like this:
public int Fn( Base a )
{
Derived b = (Derived)a;
return b.GetVal();
}
Assuming allocation doesn't change, there should be no harm in doing a cast
like this. Are there class modifiers that could handle this?
Thanks, Chris.