There is a Heritage:
// Clase A (Padre)
class A
{
public int X;
public int Y;
public A(int x, int y) { this.X = x; this.Y = y; }
}
// Clase B : Hijo
class B : A
{
public int Z; // Extendimos la clase A, en la clase B.
public B(int x, int y) : base(x, y) { Z = 0; }
}
And by calling them we can do so:
B Child = new B(2, 3); // X = 2, Y = 3, Z = 0;
A Parent = B; // Z practicamente no existe, pero puede ser accesible con un cast.
And then, apart from the inheritance, there is also something like a copy, which I think is more suited to your case, since you have two classes with the same members ...
Imagine that we have class A:
class A
{
public int X;
public int Y;
public A(...) { /* ... */ }
}
And a class B:
class B
{
public int X;
public int Y;
public B(...) { /* ... */ }
public B(A elem)
{
this.X = A.X;
this.Y = A.Y;
}
}
If you notice, in the class A
and B
we have the same attributes, what makes them different is the identifier, in the class B
I have put a copy constructor, which complies with what you are looking for and you do not need to inherit any class, so if you want to have the same values of a variable type A
in a type B
:
A MiObjeto = new A(5, 3); // X = 5, Y = 3.
B MiSegundoObjeto = new B(A); // Donde se llama al constructor copia.
If we try:
Console.WriteLine("A.X: " + A.X + ", B.X: " + B.X); // Ambos imprimen 5
Console.WriteLine("A.Y: " + A.Y + ", B.Y: " + B.Y); // Ambos imprimen 3
The difference between the two is that the copy constructor creates a new instance with all the members accessible from its own instance, while the hidden inheritance members added or extended from your new daughter class, although it can be accessed through of a cast (following the inheritance):
B Nueva = (B)A; // Obliga a la clase a convertirse en la clase hija.