[Solved] Property returns null using C# expression bodied in construction [closed]


The auto-property is not being initialized with a value, so that’s why you are getting null.

It might be important to show the difference between fields and properties.

public class Student
{
    // This is a field. It stores the actual data
    private string name;

    // This is an auto-property. The actual private field cannot be accessed directly.
    public string Name
    {
        get; set;
    }

    // This is a manual property which exposes a getter and a setter for the private field.
    public string NameProperty
    {
        get
        {
            return name;
        }
        set
        {
            name = value;
        }
    }
}

So, you’ve got several options. You might want just get rid of the field like so:

public class Student
{
   public Student() => Name = "Foo";
   public string Name
   {
      get; set;
   }
}

solved Property returns null using C# expression bodied in construction [closed]