Siddharth Sengupta Siddharth Sengupta - 1 year ago 88
C# Question

Defining an array list in c# unity.

I am trying to make an array list of integer values and run some basic math operations as seen below.

int dice1 = 4;
int dice2 = 3;
int dice3 = 6;
int dice4 = 4;
int dice 5 = 5;

ArrayList numbers = new ArrayList();
numbers[4] = dice5;
numbers[3] = dice4;
numbers[2] = dice3;
numbers[1] = dice2;
numbers[0] = dice1;

numbers[3] = numbers[3] * numbers[2];


However, the computer does not allow me to do this and produces an error "Operator "*" cannot be applied to operands of the type 'object' and 'object'". How do I fix this? I think that I have to define the array list as an array of integers... however I am not too sure. Please keep the answers simple as I am quite new to C# unity.

Thanks!

Answer Source

ArrayList stores everything as an 'object', basically the most basic type something can be in C#. You have a few options. If you want to keep using ArrayList, then you'll need to do cast the things you're multiplying, like:

numbers[3] = ((int)numbers[3]) * ((int)numbers[2])

Alternatively, you can ditch ArrayList and use the more modern List<> type. You need to add using System.Collections.Generic to the top, then your code will be like:

int dice1 = 4;
int dice2 = 3;
int dice3 = 6;
int dice4 = 4;
int dice5 = 5;

List<int> numbers = new List<int>(); //List contains ints only
    numbers[4] = dice5;
    numbers[3] = dice4;
    numbers[2] = dice3;
    numbers[1] = dice2;
    numbers[0] = dice1;

numbers[3] = numbers[3] * numbers[2]; //Works as expected

Finally, if you know that your collection will only have a certain number of things, you can use an array instead. Your code will now be:

int dice1 = 4;
int dice2 = 3;
int dice3 = 6;
int dice4 = 4;
int dice5 = 5;

int[] numbers = new int[5]; //Creates an int array with 5 elements
//Meaning you can only access numbers[0] to numbers[4] inclusive
    numbers[4] = dice5;
    numbers[3] = dice4;
    numbers[2] = dice3;
    numbers[1] = dice2;
    numbers[0] = dice1;

numbers[3] = numbers[3] * numbers[2]; //Works as expected
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download