Search code examples
c#interfacegetter-setter

Getter Setter returning null


I have an Interface

interface IPerson
{
    PersonInformation PersonInfo { get; set; }
}

And this class

public class PersonInformation
{
    public string Name{ get; set; }
}

When I implement the interface it's giving me a null error and I can't determine why. My get/set looks correct

class Employee: MyStore, IPerson
{
    private PersonInformation _perInfo;

    public override void Execute()
    {
        PersonInfo.Name = "Bill";
    }

    public PersonInformation PersonInfo
    {
        get
        {
            return _perInfo;
        }
        set
        {
            _perInfo = value;
        }
    }
}

Everything compiles but when I try to set PersonInfo.Name it's saying the object isn't set. I've played around with the get/set in the interface but that didn't change anything. I'm thinking I'm missing something so obvious...any ideas???


Solution

  • Just declaring a reference variable member does not create an object for that variable. You must set the variable to refer to an actual object instance.

    So you either want this:

    myEmployee.PersonInfo = new PersonInformation();
    myEmployee.PersonInfo.Name = "Some Name";
    

    or this in the class definition:

    private PersonInformation _perInfo = new PersonInformation();
    
    // ...
    
    myEmployee.PersonInfo.Name = "Some Name";
    

    As a further note, in the latter case you probably would be better off having the set be private, or not even defining it at all. (Note the interface definition will require otherwise, but I expect you can change that, too).

    This is because setting a mere property like .Name is still a get operation on the parent object: first you get the reference to the entire PersonInformation object, and then use the set on the object's .Name property to set the field.

    You only need to use a set for this property if you want to replace the entire object with a different one (see, for example, the first line in my sample above).