-3

I'm a beginner in C#. And whatever I tried for the following piece of code I get Index out of range exception:

    double[,] mysine = new double[0, NumPoints];

    double s = (2 * Math.PI) / NumPoints;

    for (int i = 0; i < NumPoints; i++)
    {
        mysine[0, i] = Math.Sin(i * s) + 1;
    }

The array size is NumPoints and my loop loops from zero to (NumPoints-1) which shouldn't give error. I also tried other things but couldnt work it out. Am I dong something else as wrong?

floppy380
  • 179
  • 1
  • 8
  • 3
    `double[0, X]` if size is 0 then ... – Selvin Jan 28 '21 at 15:47
  • Indeed, 0 is a "null" dimension, no dimension, nothing, does not exist, size is 0, no data allowed. But `new double mysine[1, NumPoints]` is a `one x NumPoints` matrix where D1 = 1 items and D2 = NumPoints items is the size, so the total count of items is 1 x NumPoints. That said, it is just a one dimension array... so it can be simplified, else you need more than 1 here. –  Jan 28 '21 at 16:35
  • To help you improve your skills take a look at [C# Tag Wiki](https://stackoverflow.com/tags/c%23/info) and [Learn C# from Microsoft](https://dotnet.microsoft.com/learn/csharp) in additions to online tutorials and profesional books. –  Jan 29 '21 at 06:00

1 Answers1

3
double[,] mysine = new double[0, NumPoints];

should be

double[,] mysine = new double[1, NumPoints];

The numbers between the brackets define the size of your array and not the maximumindex. So when using 0, you're actually defining an unusable array.

Truesteel86
  • 148
  • 7