Search code examples
c#algorithmsortingtostring

How to access variables inside an object?


I am creating an algorithm to fill up a train with animals based on their size and type.

Imagine an animal object in an animal class with a type and size.

/* 0 = Carnivore, Carnivores will eat other animals which are smaller or the same size.
 * 1 = Herbivore
 * Animal sizes 1, 3, 5 are currently available.
 * A trainwagon can fit a maximum of 10 points. The wagon needs to filled optimally.
 * A new wagon is added if there are still animals which need to board the train. 
 */

public Animal(int type, int size)
{
    this.type = type;
    this.size = size;
}

I need the value of an animal to sort them. So, I created an override ToString() method to get the value.

public override string ToString()
{
    string animalInformation = type.ToString() + size.ToString();
    return animalInformation.ToString();
}

I currently solved it by separating the characters of the string and converting them back to integers.

int animalType = Convert.ToString(animalInformation[0]); 
int animalSize = Convert.ToString(animalInformation[1]);

My question is: Is there another technique to access the variables in the animal object, because the double conversion impacts the performance of my algorithm in a unneccesary way.


Solution

  • Take another look at your constructor:

    public Animal(int type, int size)
    {
        this.type = type;
        this.size = size;
    }
    

    This means that type and size are data members of your Animal class, which means that any instance of Animal has a type or a size. this.type is not a variable, but rather a data member of an object, which is similar to a variable due to its changeability, but it's an inherent attribute of an object. If you do something like

    Animal animal = new Animal(1, 1);
    

    and then you cannot reach animal.type, that means that animal.type is not public, but rather private or protected. You would be able to reach it if it were public. However, don't change it to public, it's good if you protect your fields from some problematic accesses I'm not describing at this point. Instead, you can define getters, like

    public int getType() {
        return this.type;
    }
    
    public int getSize() {
        return this.size;
    }
    

    or some readonly properties and get the values by these.