- Home /
Question by
haim96 · Apr 11, 2014 at 12:38 PM ·
c#arraynullreferenceexceptionclassesproperties
Array of custom properties? (C#)
Hello,
i have a custom class:
public class jetInfo
{
public string JetName{ get; set;}
}
i need to create an array of it so i tried:
private jetInfo[] JetData = new jetInfo[3];
but when i'm trying to use it like this:
JetData[0].JetName= "Arrow";
i'm getting error in runtime:
NullReferenceException: Object reference not set to an instance of an object
what am i doing wrong?
thanks!
Comment
Best Answer
Answer by Rustam-Ganeyev · Apr 11, 2014 at 12:41 PM
When you do
private jetInfo[] JetData = new jetInfo[3];
you initialize array, where all its elements are null. All you need to do is:
JetData[0] = new jetInfo();
before
JetData[0].JetName= "Arrow";
P.S. I'd recommend to initialize array contents before using:
for (int i = 0; i < JetData.Length; ++i) {
JetData[i] = new JetInfo();
}
i tought that =new jetInfo[3];
already initialize the array...
works like a charm! thanks...
Actually, =new jetInfo[3]
initializes the array. But array is an object that contains links to other objects(jetInfo), so you need to initialize object in array to use.