fmwavesrgr8
fmwavesrgr8

Reputation: 81

Why is my C# object null after I have instantiated it? (Or have I not done that properly?)

Why is my C# object null after I have instantiated it?

I either don't know how to instantiate a class in C#, or there is a trick with 2D matrices that I'm missing here. (Either way I'm new to it all, and I limit myself to asking one question on Stack Overflow per day, so go easy with the downvotes...)

My program is a Win8 app.

I have a C# class with three members. They are:

class CMyClass
    {
        public double[][] matrix1;
        public double[][] matrix2;
        public double[][] matrix3;
    }

And I try to instantiate it in my program like this:

CMyClass myObject = new CMyClass();

Then if I try to access any of the matrix members to read or write to the arrays I get a null reference exception error that say the object isn't instantiated. Is something missing from my class or is the problem with the way I try to instantiate the object?

Upvotes: 1

Views: 8500

Answers (5)

fmwavesrgr8
fmwavesrgr8

Reputation: 81

Thanks folks. This seems to be the best working solution for me:

> class CMyClass
> {
>     public double[][] matrix1; 
>         
>     public CMyClass(int x)
>     {
>     matrix1 = new double[x][];

>      for (int i = 0; i < x; i++)
>      { matrix1[i] = new double[x]; }
>     }
> }

Then in program:

int matrixSize = 10;
CMyClass MyNewObject = new CMyClass(matrixSize);

Now I can read and write to the elements of the matrix.
Solved! =D

Upvotes: 0

Paresh
Paresh

Reputation: 564

Just tried with tiny console app.

static void Main(string[] args) {
      CMyClass myObject = new CMyClass();                 
      myObject.matrix1= new double[1][] ;
      myObject.matrix1[0] = new double[1];
      Console.WriteLine(myObject.matrix1[0][0]);     

      }

Upvotes: 1

James Wood
James Wood

Reputation: 17562

You have only instantiated the CMyClass, you haven't instantiated any of the members of the class.

Try adding a default constructor to the class, and in the constructor set the member values.

public CMyClass()
{
    matrix1 = new double[][] {};
    ...
}

Upvotes: 1

Fran
Fran

Reputation: 6520

Because you haven't instantiated those items yet.

class CMyClass
{
    public double[][] matrix1;
    public double[][] matrix2;
    public double[][] matrix3;

    public CMyClass()
    {
        matrix1 = new double[][] {};
        matrix2 = new double[][] {};
        matrix3 = new double[][] {};
    }
}

Upvotes: 5

pm100
pm100

Reputation: 50190

Creating an instance of an object initializes its members to their default values. For reference types (like an array) this means null.

You need to explicitly create an empty array of the size you want in the objects constructor;

matrix1 = new double[4][2];

you can also put it in the declaration of the member (but that would be odd since you probagbly dont know what size you want - or maybe you do)

Upvotes: 3

Related Questions