Reputation:
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);
}
}
Upvotes: 1
Views: 7664
Reputation:
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;
}
Upvotes: 0
Reputation: 2701
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;
}
}
Upvotes: 0
Reputation: 4550
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;
}
}
Upvotes: 1
Reputation: 979
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);
}
}
Upvotes: 1