-1

Am using winforms in c# with visual studio 2015

This is my class

public class advmessage
{
    public string[] message;
}

so then in the load event of form1 I do this

   advmessage newadvmessage = new advmessage();
   newadvmessage[1]="Hello";

and for that assignment, it throws the exception for null reference and says object reference not set to an instance of an object.

So if I have a class that does not need to be an array, everything works find, but on the ones that use arrays, is where it has the exception.

Also, I do not have a get set or return for any of the classes, and that might b the problem but yet when I added the { get; set; } in there it still had a problem. I could understand a null reference, if I referenced a null string, but I am just trying to set the message property that will be shown in a text box to the user.

Any help would be greatly appreciated.

Larryrl
  • 91
  • 1
  • 6
  • Have you stepped through the code in the debugger? Most likely your array `newadvmessage` has not been initialized. – Tim Jul 28 '16 at 18:22
  • The `get` and `set` (i.e., property vs a field, what you have right now is a field) have nothing to do with the error. From a best practices perspective, you should be using properties, not fields. Fields should be private to the class. – Tim Jul 28 '16 at 18:23

1 Answers1

0
public class advmessage
{
    public advmessage(size)
    {
        message = new string[size];//or whatever size you want.
    }
    public string[] message;
}

advmessage newadvmessage = new advmessage(5);
newadvmessage.message[1]= "Hello";
Robert Columbia
  • 6,012
  • 14
  • 28
  • 36
  • Ok, so when I did that it wanted the brackets to go directly after the newadvmessage and before the .message property. – Larryrl Jul 28 '16 at 18:35