Use of unassigned local variable (Object)

2019-09-21 16:33发布

问题:

Person tempPerson;

Console.WriteLine("Enter the name of this new person.");
tempPerson.Name = Convert.ToString(Console.ReadLine());

Console.WriteLine("Now their age.");
tempPerson.Age = Convert.ToInt32(Console.ReadLine());

peopleList.Add(tempPerson);

RunProgram();

At tempPerson.Name, the error list displays "Unassigned use of local variable 'tempPerson'. Below is the class where each Person object is created.

class Person : PersonCreator
{
    public Person(int initialAge, string initialName)
    {
        initialAge = Age;
        initialName = Name;
    }
    public int Age
    {
        set
        {
            Age = value;
        }
        get
        {
            return Age;
        }
    }
    public string Name
    {
        set
        {
            Name = value;
        }
        get
        {
            return Name;
        }
    }
}   

I don't understand why this is a problem. At tempPerson.Age, there is no problem at all. Running the program with only tempPerson.Age brings no errors. Is there a problem with my Person class?

回答1:

tempPerson is never initialized to a Person object, so it is null - any call to any member of the variable will result in a NullReferenceException.

You must initialize the variable before usage:

var tempPerson = new Person();


回答2:

You do not create an object by defining a class or declaring a variable of a class type. You must create an object by calling new on the class, otherwise the variable is initialized with null. Do the following:

Person tempPerson = new Person ();

Console.WriteLine("Enter the name of this new person.");
tempPerson.Name = Convert.ToString(Console.ReadLine());


回答3:

Your Person class is wrong, it should be:

class Person : PersonCreator
{
    public Person(int initialAge, string initialName)
    {
        Age = initialAge;
        Name = initialName;
    }
    public int Age
    {
        set;
        get;
    }
    public string Name
    {
        set;
        get;
    }
} 


回答4:

Your variable tempPerson is just declared, but not initialized. You have to call the constructor of Person, but this requires an empty constructor:

Person tempPerson = new Person();

An other way to solve this, i would implement like the follow:

Console.WriteLine("Enter the name of this new person.");
string name = Convert.ToString(Console.ReadLine());

Console.WriteLine("Now their age.");
string age = Convert.ToInt32(Console.ReadLine());

peopleList.Add(new Person(name, age));