-3

I'm newbie in C#. I know C and C++ language. Currently I have a C# related project. So, I just want to know basic concept about C#.

In C#, If I give negative array index, then What happens? Is it Undefined behaviour?

Like :

int [] arr = {1,2,3};
Console.WriteLine("{0}", arr[-1]);
Jonathan Wood
  • 61,921
  • 66
  • 246
  • 419
msc
  • 32,079
  • 22
  • 110
  • 197

3 Answers3

12

Your program will throw an IndexOutOfRangeException exception any time the index is out of the range of valid indexes for that array.

Had you taken a second to try it, you would've seen that for yourself.

Jonathan Wood
  • 61,921
  • 66
  • 246
  • 419
0

If you access an array out of its index range, you'll get an System.IndexOutOfRangeException. This exception you'll get for any negative index or any index larger or equal array.Length.

milbrandt
  • 1,366
  • 2
  • 14
  • 19
0
int [] arr = {1,2,3};

Compiler will transform the above syntactic sugar internally as

 int [] arr = new int[] {1,2,3};

so arr length is calculated as 3 by the compiler automatically.

Compiler will not allow you define array of unknown size.

int[] arr=new int[];//compiler error,array creation must have size.

So below statement

Console.WriteLine(arr[-1]);

will throw an unhandled exception of type 'System.IndexOutOfRangeException'.

Alex
  • 782
  • 7
  • 19
Hameed Syed
  • 3,531
  • 2
  • 18
  • 27
  • arr={1,2,3} internally will be transformed as int[].And also why -1 is not allowed because array index starts from 0 and thats because it uses pointers internally and below 0 is junk value and hence compiler warns from giving invalid indices.And also I am tying in mobile didnt see your answer before. – Hameed Syed Feb 03 '18 at 14:19