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.

Alexei Levenkov
  • 98,904
  • 14
  • 127
  • 179
Sona Rijesh
  • 1,041
  • 7
  • 32
  • 62
  • http://msdn.microsoft.com/en-us/library/aa288453(v=vs.71).aspx – Adil Mar 15 '13 at 04:49
  • If you post some code I might be able help you identify the source of your problem – p.s.w.g Mar 15 '13 at 05: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. – Alexei Levenkov Mar 15 '13 at 05:31

1 Answers1

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);
p.s.w.g
  • 146,324
  • 30
  • 291
  • 331
  • 1
    @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. – p.s.w.g Mar 15 '13 at 05:03
  • 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.Add` instead. – p.s.w.g Mar 15 '13 at 05:20
  • 2
    @Sona what errors are you getting? – rhughes Mar 15 '13 at 05:31
  • This means that your index is too high or low. How big is the array, and what is the index value? – rhughes Mar 15 '13 at 05:36
  • i given public int[] iArray = new int[15]; – Sona Rijesh Mar 15 '13 at 05:43
  • @Sona if you initialize `iArray` as `new int[15]` then you can use index values from 0 to 14 (`iArray.Length - 1`). Trying to use index values less than 0 or greater 14 will result in an `IndexOutOfRangeException` – p.s.w.g Mar 15 '13 at 05:50
  • iArray[1]=123; i given like this.shows error – Sona Rijesh Mar 15 '13 at 05:54