How can I do something like the following?
My A object is null after calling GetB even though A inherits from B.
class Program
{
public class A : B
{
}
public class B
{
}
static void Main(string[] args)
{
A a = GetB() as A;
Console.WriteLine(a == null); // it is null!
Console.WriteLine("Console.ReadKey();");
Console.ReadKey();
}
public static B GetB()
{
return new B();
}
}
You’re trying to downcast your B into an A. You can’t do that, nor does it makes sense because we do not know if a B is going to be an A. It would be better to build a constructor in your
Aclass that takes aBas a parameter.