Solved

# Car otherCar = obj as Car;

Posted on 2014-09-18
176 Views
Could someone explain me what this line really do from the following code?
Car otherCar = obj as Car;   Does it mean deaclaring an obj as a Car but why is Car otherCar equal to it?

``````class Car : IComparable
{
public string Name { get; set; }
public int MaxMph { get; set; }
public int Horsepower { get; set; }
public decimal Price { get; set; }

public int CompareTo(Object obj) {

if (!(obj is Car))

throw new ArgumentException("object is not a car");
Car otherCar = obj as Car;
return Name.CompareTo(otherCar.Name);

}
``````
0
Question by:yguyon28
[X]
###### Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

• Help others & share knowledge
• Earn cash & points
• 2

LVL 40

Assisted Solution

Kyle Abrahams earned 250 total points
ID: 40331384
public int CompareTo(Object obj) {

// if the object is not a car throw an exception
if (!(obj is Car))
throw new ArgumentException("object is not a car");

Car otherCar = obj as Car;
return Name.CompareTo(otherCar.Name);

}

Essentially the variable "obj" is passed in as an object.  Since it's an object, you don't have access to all of the properties of the class.

Car otherCar = obj as Car;

This line makes obj an actual Car (typeof Car)  and assigns it to the variable otherCar.  Essentially "obj as Car" is casting the object as a Car.

return Name.CompareTo(otherCar.Name);

This then compares the Name property of the current instance with the name property of the car that was passed in.

you can combine the two lines like this:
return Name.CompareTo((obj as Car).Name);
or
return Name.CompareTo( ((Car)obj).Name);

I wouldn't have used the otherCar variable in this case.

Hope that helps.
0

LVL 75

Expert Comment

ID: 40331496
Another way to think about is like this:

If I say to you, "My red car, which has 2 doors, and 4 wheels, is very fast" then you can begin to develop a mental picture of what my car looks like. If I instead say, "My vehicle is very fast," then can you say for certain that I am talking about my 2-door, red car? What if I have a boat? What about a moped? When I say "vehicle", I am treating my car--in this case--more abstractly than if I refer to it as a car. A car is a concrete type of vehicle: I know what a car looks like(for the most part), but a vehicle could be any number of things.

So, what does that kind of imagery look like in code? Well a Car might be:
``````Car c = new Car();
c.Color = "red";
c.Doors = 4;
c.Wheels = 4;
``````
What about a Vehicle? Well, we can't say for certain, because a vehicle could be any number of things, with any number of somewhat common properties. Perhaps Color is common among all vehicles; Wheels surely won't be--I mean, boats don't have wheels, right? But I can still treat a car as a generic vehicle, right?
``````Vehicle v = new Car();
``````
And I can set the color since it's common:
``````v.Color = "red";
``````
But now if I want to set the wheel count I have a problem:  only some vehicles have wheels. I need to treat this thing as a car again. I can do that by way of a cast:
``````((Car)v).Wheels = 4;
// OR
(v as Car).Wheels = 4;
``````
The only difference between the first line and the second line above is that the as operator will return null if the thing being cast is not actually of the type being cast to. In other words, if the thing that v pointed to was actually a Boat:
``````Vehicle v = new Boat();
``````
...then casting to a Car would not work. However, whereas a straight cast will fail with an InvalidCastException, as will not. It return null as I mentioned. This means that any time you use as you will want to make sure that you are checking for possible null returns from it.
0

LVL 30

Accepted Solution

anarki_jimbel earned 250 total points
ID: 40331522
I believe the question is answered by Kyle Abrahams. Just some comments.

"Does it mean declaring an obj as a Car but why is Car otherCar equal to it?"

The line below is an assignment, not an equality.
Car otherCar = obj as Car;

If you have a declaration ' Car otherCar;', then the otherCar variable points to nowhere.
After the assignment it points to the object 'obj' and you may access all Car properties etc.

Regarding. the last comment about combining the two lines. Personally I'm not a supporter for this. Often developers misuse this and code becomes completely unreadable and hard for debugging. Especially for or beginners: the simpler the better.
0

LVL 75

Expert Comment

ID: 40331795
Happy to not help?   : \
0

## Featured Post

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

International Data Corporation (IDC) prognosticates that before the current the year gets over disbursing on IT framework products to be sent in cloud environs will be \$37.1B.
Performance in games development is paramount: every microsecond counts to be able to do everything in less than 33ms (aiming at 16ms). C# foreach statement is one of the worst performance killers, and here I explain why.
This is a high-level webinar that covers the history of enterprise open source database use. It addresses both the advantages companies see in using open source database technologies, as well as the fears and reservations they might have. In this…
Monitoring a network: why having a policy is the best policy? Michael Kulchisky, MCSE, MCSA, MCP, VTSP, VSP, CCSP outlines the enormous benefits of having a policy-based approach when monitoring medium and large networks. Software utilized in this v…
###### Suggested Courses
Course of the Month1 day, 13 hours left to enroll