Car otherCar = obj as Car;

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

yguyon28Asked:
Who is Participating?
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

Kyle AbrahamsSenior .Net DeveloperCommented:
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
käµfm³d 👽Commented:
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
anarki_jimbelCommented:
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

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
käµfm³d 👽Commented:
Happy to not help?   : \
0
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
C#

From novice to tech pro — start learning today.

Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.