I'm trying to make this:
class A {
//attibutes
}
class B : A {
public int classBAttribute = 5;
// other attributes and methods
}
My question is this if I have an instance of A class how can i get the instance of the B class or access his attributes?
B b = new B();
Application.Add(b);
//other form
A a = Application.GetA();
B b = getBFromA(a);// ??? Note: B b = a as B; does't work i tried
You cannot do this -- there is no magical way to create derived objects from base objects in general.
To enable such a scheme class
B
would need to define a constructor that accepts anA
argument:which you can then use as
Of course after this
a
andb
will be completely different objects; changing one will not affect the other.You should also get the terminology right in order to avoid confusion:
classBAttribute
is not an attribute, it is a field.How would your program know an instance of A is actually of type B?
An instance of B could be used as A (as B is a specialization of A), but the opposite is not possible.
Maybe I don't fully understand the question or the answers, but...
Casting an
A
to aB
should work (as long as theA
is actually (also) aB
).