user8389423435
user8389423435

Reputation: 3

Using properties of a class on a generic object

essentially what I am trying to do is the following : I have a class called Animals that reads some animals that has several properties associate with it such as age,type,birth date etc. What I'm facing problem with is the CompareTo() method which takes a generic object as a parameter, checks if it's of the type Animal and if so compares the name associated with this object to the instance of the name associate with the instance of the Animal.

I tried using

this.Name.CompareTo(object.Name);

but obviously it doesn't work for this case since Name isn't defined within object.Is there a way around this ? Being able to compare properties inside an object, knowing that it is of type Animal, to properties within an instance of the Animal class ? Thanks in advance.

Upvotes: 0

Views: 58

Answers (2)

Rufus L
Rufus L

Reputation: 37020

You can use the as operator to cast the object to an Animal. If the cast succeeded, then you can compare the name properties. If the cast failed, the object will be null (and you normally return 1 if the other object is null).

public int CompareTo(object obj)
{
    var other = obj as Animal;

    if (other == null) { return 1; }
    if (this.Name == null) return (other.Name == null) ? 0 : -1;
    return this.Name.CompareTo(other.Name);
}

Upvotes: 3

Mike Cowan
Mike Cowan

Reputation: 919

You need to cast the object to an Animal before comparing the names:

public int CompareTo(object obj)
{
    if (obj == null)
    {
        return 1;
    }

    if (obj is Animal)
    {
        Animal other = (Animal)obj;
        return this.Name.CompareTo(other.Name);
    }

    return 1;  // or whatever behavior you want if obj is not an Animal
}

Upvotes: 0

Related Questions