JayPhillips JayPhillips - 22 days ago 6
C# Question

Object property causing error

I have this object property called "Categories" which can be shown here:

private List<Category.Categories> _categories;
public List<Category.Categories> Categories
{
get { return _categories; }
set
{
if (!Enum.IsDefined(typeof(Category.Categories), value))
{
_categories = null;
}

_categories = value;
}
}


I try to return my object with this property but all I get is a `System.NullReferenceException: Object reference not set to an instance of an object. error. If I remove this property from the instantiaziation return then I have no problems. I'm not sure why this causes an error. The property only wants to accept enums from this class:

public class Category
{
public enum Categories
{
Footwear,
Electronics,
Jewellery,
Restaurants,
Services,
Apparel
}
}


Finally this is how I'm setting the property:

Categories = { Categories.Apparel }

Answer

You have to initialize your list to store list form the set property

private List<Category.Categories> _categories = new List<Category.Categories>();