I have this situation
public class Base
{
public Basedef def;
}
public class A : Base
{
}
public class B : A
{
public int GetBar()
{
return def.bar;
}
}
public class BaseDef
{
}
public class ADef : BaseDef
{
public int foo;
}
public class BDef : ADef
{
public int bar;
}
As you an see, there is an error in method B:GetBar(), because def have no access to bar, but if you make...
public int GetBar()
{
return (def as BDef).bar;
}
should work, but i want to avoid casting, how to get properties from definition using reference created in Base class without using casting?
Why avoid cast?, because is prone to runtime errors and is easier to introduce bugs, I want type-safe coding.
What I am trying to do
public class Factory
{
public static Base<BaseDef> Create(BaseDef d)
{
if(d is BDef)
return new B(); //Error, can not convert B to Base<BaseDef>
}
}
public class Program
{
B instance = Factory.Create(new BDef()); //Error, can not convert to Base<BaseDef> to B
}
I am looking for an elegant solution
bye!