-1

Below code creates the error message in the subject line. Could you please help? I am trying to instantiate below class as an object. I think the error is caused by the array that I am trying to declare.

class DataStuff
{
    public double G { get; set; }
    public double[,] M { get; set; }

    public void UpdateData()
    {
        G = 500;
    }

    public void UpdateMatrixData()
    {
        for(int i=0; i<2; i++)
        {
            for (int j = 0; j < 2; j++)
            {
                M[i, j] = i + j;
            }
        }
    }

}
Ujae Kang
  • 157
  • 1
  • 8

2 Answers2

1

You should create M[,] matrix instance before using it:

class DataStuff {
  ...
  // M is null; an instance should be created 
  // Usually, "private set;" instead of "set" is a better design
  public double[,] M { get; set; } 

  public DataStuff() {
    M = new Double[2, 2]; // <- M is created in the constructor
  } 
  ...
}
...
DataStuff test = new DataStuff();
test.UpdateMatrixData(); 
Dmitry Bychenko
  • 180,369
  • 20
  • 160
  • 215
  • Dmitry, so how about public double G { get; set; }? Don't I need to do anything to it? Is it because M is an array and it is different? – Ujae Kang Apr 15 '14 at 08:39
  • 1
    A double is a value type and can be used directly. An array (of anything) is a reference type and has to be `new`ed. – George T Apr 15 '14 at 08:44
  • 1
    @Ujae Kang: `Double` type in `Double G` is a struct, not class (as array is) so you don't need creating `G`. In fact, `G` will be initialized with `0.0` value – Dmitry Bychenko Apr 15 '14 at 08:44
  • How on earth can you use **M** for property and and array..? this is wrong code! – HackerMan Apr 15 '14 at 08:48
  • @HackerMan: You can use any type (array included) in property. Not that good design, but still is possible. – Dmitry Bychenko Apr 15 '14 at 08:52
1
    for (int j = 0; j < 2; j++)
    {
        M[i, j] = i + j;//if you are trying to access the property..this is wrong!
//you cant access the property like an array
    }

if you want to access the property like array use indexer

public double[,] this[int i,int j]
{
get;
set;//enter your code here!
}
HackerMan
  • 904
  • 7
  • 11