0

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);
        }
    }

4 Answers4

1

That is a bad practice. You have to make your field 'provinceCode' to private

private string provinceCode;

Your property has to be only public Which can only be access.

public string ProvinceCode
  {
    get 
     {
        return provinceCode;
     }
   set 
    {
       provinceCode = value;
    }     
 }


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); 

    }
}
Code OverFlow
  • 743
  • 12
  • 26
0

That is right behaviour , you have not return any value for this property or set value so it is null.

     public string ProvinceCode
    {
       get; set;
    }

if you want to return the provinceCode

  private string provinceCode;

  public string ProvinceCode
  {
    get 
     {
        return provinceCode;
     }
   set 
    {
       provinceCode = value;
    }     
 }
Devesh
  • 4,132
  • 1
  • 13
  • 25
0

If you want to have some default value if ProvinceCode is not set you could use lazy loading:

private string _provinceCode;

public string ProvinceCode
{
  get 
  {
     if(string.IsNullOrEmpty(_provinceCode)) {
        _provinceCode = "CODE";
     }
     return _provinceCode;
  }
  set 
  {
     _provinceCode = value;
  }     
}
Tadija Bagarić
  • 2,164
  • 2
  • 25
  • 41
0

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;
    }