-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
  • 65,341
  • 71
  • 269
  • 466
msc
  • 33,420
  • 29
  • 119
  • 214

3 Answers3

13

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
  • 65,341
  • 71
  • 269
  • 466
1
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
  • 790
  • 7
  • 20
Hameed Syed
  • 3,939
  • 2
  • 21
  • 31
  • 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
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,438
  • 2
  • 15
  • 20