I have four classes like:
class BaseA { }
public class DerivedA : BaseA { }
public class BaseB
{
public BaseA SomeProperty { get; set; }
}
public class DerivedB : BaseB
{
public new DerivedA SomeProperty { get; set; }
}
which are used in program like:
static void Main(string[] args)
{
var derivedB = new DerivedB();
derivedB.SomeProperty = new DerivedA();
SomeMethod(derivedB);
}
static void SomeMethod<T>(T param) where T : BaseB
{
var tmp1 = param.SomeProperty; // null
var tmp2 = (param as DerivedB).SomeProperty; // required value
var tmp3 = (param as T).SomeProperty; // null
}
If I pass in SomeMethod
a parameter of type DerivedB
, param has 2 properties SomeProperty
- of base and derived class types. But no matter of what type is param
, it is treated as BaseB
class and I have to explicitly cast it to required type to get the right SomeProperty
value. Casting to T does not help.
Should I cast the param variable to its own type or can I get at least a property with not-null value?