Reputation: 35
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!
Upvotes: 1
Views: 25183
Reputation: 7605
You can do it in one line:
List<int> numbers = new List<int>{ 4, 3, 6, 4, 5 };
Upvotes: 0
Reputation: 460
You need to parse the object to string then to int value then use it with * operator.But you firstly have to initialize the arraylist with null values then assign number values So that, use following code that I made clear changes for you.
int dice1 = 4;
int dice2 = 3;
int dice3 = 6;
int dice4 = 4;
int dice5 = 5;
int capacity=5;
ArrayList numbers = new ArrayList(capacity);
for (int i = 0; i < capacity;i++ )
{
numbers.Add(null);
}
numbers[4] = dice5;
numbers[3] = dice4;
numbers[2] = dice3;
numbers[1] = dice2;
numbers[0] = dice1;
numbers[3] = (int.Parse(numbers[3].ToString()) * int.Parse(numbers[2].ToString()));
print(numbers[3]);
Upvotes: -1
Reputation: 534
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
Upvotes: 2
Reputation: 2313
Avoid using array list
Use List<int>
or int[]
Then the objects contained are typed instead of being object
Upvotes: 0