Arrays in C#

  • Thread starter Thread starter Krish
  • Start date Start date
K

Krish

I think I have understood Arrays incorrectly in C#.

I declared the following

int[] myIntArray = new int[5] { 1,2,3,4,5 };

I assumed that this has created an Integer Array, and to access any element
I would have to do the following : myIntArray[4];

However I see that there is also another way of doing this I am not sure
why people would use this call.

int myRes = (int) (myIntArray.GetValue(1));

I think I have to do this only if my Array is an array of Objects.

Please clarify.
 
Array class implements IList as you could do in your own class. Hence, it
implements the "Item" property with get and set accessors which provides the
ability to access a specific element in the collection by using the
"myCollection[index]" syntax. So the get accessor for Array, actually calls
"this.GetValue(index)". So they are effectively equivilent. Calling
GetValue(index) directly, removes the additional method call, but using the
[index] syntax is probably more natural for indexing arrays. hth
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Back
Top