Search code examples
c#getter-setter

Getter returning NULL c#


When accessing the property using the getter i'm getting a NULL. I've changed it to public to test if everything else is working and yeah nothing else is wrong.

HTProvince Class

public string provinceCode;

public string ProvinceCode
{
    get; set;
}

Form

public Form1()
{
    //HTGetProvinces() returns a list of provinces
    InitializeComponent();
    List<HTProvince> provinceList =
        HTProvince.HTGetProvinces();

    foreach (HTProvince x in provinceList)
    {
        //Works. Adds items the province code property of for each item to my list
        provincesListBox.Items.Add(x.provinceCode); 
        //throws null exception. Doesn't work
        provincesListBox.Items.Add(x.ProvinceCode);
    }
}

Solution

  • This is auto-properties introduced in C# 3.0 and later

    Change the property to:

    private string provinceCode { get; set; }
    

    Instead of a separate method:

    public string ProvinceCode
    {
        get; set;
    }