0

How can i create a int array in class.

And i have to add values to that array.

Not to a specific key.

i declared array as

public int[] iArray;

from function i have to insert values of i to array. My i values gets change. So i have to save those in a array.

iArray[] = i; 

But it shows error.

3
  • msdn.microsoft.com/en-us/library/aa288453(v=vs.71).aspx Commented Mar 15, 2013 at 4:49
  • If you post some code I might be able help you identify the source of your problem Commented Mar 15, 2013 at 5:07
  • I would recommend to try to write some basic code in Visual Studio first and read help on errors. If Unity3d environment shows you errors check error codes (like CS1234) in the error messages and search for them - usually you get useful details. (I.e. that you must assign values to variables before using, or using index when trying to set element of array). Side note: please avoid "I know nothing/thankyou" text in the question and instead inline complete error messages. Commented Mar 15, 2013 at 5:31

1 Answer 1

5

Handling arrays is pretty straight forward, just declare them like this:

int[] values = new int[10];
values[i] = 123;

However, arrays in C# have fixed size. If you want to be able to have a resizeable collection, you should use a List<T> instead of an array.

var values = new List<int>();
values.Add(123);

Or as a class property:

class SomeClass
{
    private List<int> values = new List<int>();

    public List<int> Values { get { return this.values; } }
}

var someInstance = new SomeClass();
someInstance.Values.Add(123);
Sign up to request clarification or add additional context in comments.

7 Comments

@Sona i just represents an indexer (as in for(var i = 0...). The NullReferenceException is raised because the Values property isn't initialized. I've updated by example to show how to initialize the list properly.
You must use an indexer to set an item in an array (as in my example). If you don't want to do that use List<T>.Add instead.
@Sona what errors are you getting?
This means that your index is too high or low. How big is the array, and what is the index value?
i given public int[] iArray = new int[15];
|

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.