Link to home
Start Free TrialLog in
Avatar of Camillia
CamilliaFlag for United States of America

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.

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; }
		}

Open in new window

SOLUTION
Avatar of Chinmay Patel
Chinmay Patel
Flag of India image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
ASKER CERTIFIED SOLUTION
Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
SOLUTION
Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of Camillia

ASKER

yes! good. Just double checking. Made me feel better that I knew the answer :) group interviews are stressful. I decided to leave my current job and my moody, abusive manager (those of you who've been helping me know my situation :))
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).
I have another one that I'm working thru. I'll post another question to double check my explanation.