How to access the properties of a daughter class from the parent class instance

0

Assuming I have the following classes

class Vehiculo 
{
    public string Nombre { get; set; }
}

class Auto : Vehiculo
{
    public string CantidadRuedas { get; set; }
}

and what I want to do is the following

Vehiculo vehiculo = new Auto();
// Como acceder a las propiedades de auto?
// al intentar hacer lo siguiente intellisense me dice que vehiculo no tiene tal propiedad
Console.log(vehiculo.CantidadRuedas);
// al intentar usar un cast me sigue sin reconocer la propiedad
Console.log((Auto)vehiculo.CantidadRuedas);

The question is: how do I access the properties of the child element in that case?

    
asked by LPZadkiel 04.12.2018 в 20:31
source

2 answers

1

You have to wax the casting operation in parentheses so that you can return the instances you want:

Console.Log(((Auto)vehiculo).CantidadRuedas);

Or you can also use the as operator that converts the reference to the desired type, but you will still have to enclose the operation inside parentheses to be able to access the instance:

 Console.Log( (vehiculo as Auto).CantidadRuedas );
    
answered by 04.12.2018 / 20:45
source
1

If you want to access the properties of the car you should do it this way

Auto vehiculo = new Auto();
Console.log(vehiculo.CantidadRuedas); 

In order for what you want to do to work correctly, you should know that the one that has 'quantityRed' is the son, not the father. Therefore you must create a variable of the type 'Auto'

But if you want to cast it, as shown in the question, the solution is as follows

Console.log(((Auto)vehiculo).CantidadRuedas);

What you have to cast is the variable, not the value returned

    
answered by 04.12.2018 в 20:44