-3

A newbie to C# here (more C++ for many years) struggling with perhaps a simple problem, but unable to diagnose.

Class definition:

public class myClass{
String prop1, prop2,... propn;
public void setValues(String input){
prop1 = input.Substring(1,5);
prop2 = input.Substring(6,10);
...
propn = input.Substring((n-1)*5+1,n*5));
}
public getProp1() {return prop1;}
public getProp2() {return prop2;}
...
public getPropn() {return propn;}
}

In program

    myClass[] Entries = new myClass[50];
    int i=0;
    String Line
    while(i<=49){
    Line = inputFile.ReadLine(); //<--System.NullReferenceException thrown here at run-time
    Entries[i++].setValues(Line);
    }

Any help would be sincerely appreciated to figure out this run-time exception. I'm using Visual Studio 2019, and this is a console application...if that's relevant.

Thanks in advance!

  • 1
    The exception is actually at the line below, i.e. Entries[i++].setValues(Line); – Satyam Bendapudi Oct 19 '20 at 21:02
  • where's your `inputFile` defined? – Sten Petrov Oct 19 '20 at 21:23
  • Thanks AStopher. That was helpful to figure out that the class itself was apparently null, even though I have a constructor that initializes all properties. [perhaps an extension to the original post but...] shouldn't the constructor execute upon creation of the array of classes, and each instance of the class be initialized? – Satyam Bendapudi Oct 19 '20 at 21:28
  • Hi Sten. The input file is defined earlier in my code using StreamReader. I can confirm that it's opening and the "Line" value shows correct in watch. – Satyam Bendapudi Oct 19 '20 at 21:29

1 Answers1

0

This line:

 myClass[] Entries = new myClass[50];

Creates an array filled with null's for values. So Entries[i++] will return you a null resulting in the error in your question. You can create an object of your type with new for example like this:

while(i<=49)
{
    Line = inputFile.ReadLine(); 
    var instance  = new myClass();
    instance.setValues(Line); 
    Entries[i++] = instance ;
}
Guru Stron
  • 21,224
  • 3
  • 19
  • 37