I am getting
Object reference not set to an instance of an object
error when trying to call the GetPersonName() method in my main method.
Can any one explain me why this error is happening ?
Here is my code. Thank You
//My Class
class Program
{
// Main Method
static void Main(string[] args)
{
DMO dmo = GetPersonName();
Console.Write(dmo.PersonArray[0].Name);
Console.ReadKey();
}
private static DMO GetPersonName()
{
DMO dmo = new DMO();
dmo.PersonArray[0] = new Person { Name = "XXXXXX" }; // Object reference not set to an instance of an object.
return dmo;
}
}
// My Data Model Object
public class DMO
{
private Person[] _personArray;
public Person[] PersonArray
{
get { return _personArray; }
set { _personArray = value; }
}
}
public class Person
{
private string _name = "";
public string Name
{
get { return _name; }
set { _name = value; }
}
}
In your
DMOclass, you never instantiate your_personArray.When instantiating
DMO_personArrayisnull, so this code:fails, as
dmo.PersonArrayisnulland you can’t access any of its members.You need to instantiate the whole array: