Camillia
asked on
Explain this code
I'm going over some sample code for my interview on Friday... code practices I'm finding.
This is the sample code. I run it and I get errors on 2 lines but I'm not quite sure about the explanation. I'll add my comments in the code below as to why I think the error occurs.
This is the sample code. I run it and I get errors on 2 lines but I'm not quite sure about the explanation. I'll add my comments in the code below as to why I think the error occurs.
protected void Page_Load(object sender, EventArgs e)
{
object car = new Car {MaxSpeed = 180};
object processor = new Processor { MaxSpeed = 2500 };
Vehicle v1 = (Vehicle) car;
int speed = v1.MaxSpeed;
Vehicle v2 = car as Vehicle;
int s2 = v2.MaxSpeed;
Vehicle v3 = (Vehicle)processor; //** error here with invalid cast. Why can't I cast processor to vehicle...because processor is not inheritng from Vehicle?
int s3 = v3.MaxSpeed;
Vehicle v4 = processor as Vehicle; //*** this comes out as null. I think because inheritance is "is a" relationship but processor is not a vehicle. Is this correct?
int s4 = v4.MaxSpeed; //*** null error here because v4 is null
}
public class Vehicle
{
public int MaxSpeed { get; set; }
}
public class Car :Vehicle{}
public class Processor
{
public int MaxSpeed { get; set; }
}
SOLUTION
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
ASKER CERTIFIED SOLUTION
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
SOLUTION
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
YAY! (Not for stressful interviews BUT for quitting).. All the best for the new one (I do believe that it is really hard to find a good manager.. if you find one let me know).
ASKER
I have another one that I'm working thru. I'll post another question to double check my explanation.
ASKER