Solved

Car otherCar = obj as Car;

Posted on 2014-09-18
4
160 Views
Last Modified: 2014-09-18
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);
        
        }

Open in new window

0
Comment
Question by:yguyon28
  • 2
4 Comments
 
LVL 40

Assisted Solution

by:Kyle Abrahams
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 74

Expert Comment

by:käµfm³d 👽
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;

Open in new window

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();

Open in new window

And I can set the color since it's common:
v.Color = "red";

Open in new window

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;

Open in new window

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();

Open in new window

...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 29

Accepted Solution

by:
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 74

Expert Comment

by:käµfm³d 👽
ID: 40331795
Happy to not help?   : \
0

Featured Post

Highfive Gives IT Their Time Back

Highfive is so simple that setting up every meeting room takes just minutes and every employee will be able to start or join a call from any room with ease. Never be called into a meeting just to get it started again. This is how video conferencing should work!

Join & Write a Comment

Today is the age of broadband.  More and more people are going this route determined to experience the web and it’s multitude of services as quickly and painlessly as possible. Coupled with the move to broadband, people are experiencing the web via …
Calculating holidays and working days is a function that is often needed yet it is not one found within the Framework. This article presents one approach to building a working-day calculator for use in .NET.
Sending a Secure fax is easy with eFax Corporate (http://www.enterprise.efax.com). First, Just open a new email message.  In the To field, type your recipient's fax number @efaxsend.com. You can even send a secure international fax — just include t…
This video explains how to create simple products associated to Magento configurable product and offers fast way of their generation with Store Manager for Magento tool.

747 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

9 Experts available now in Live!

Get 1:1 Help Now