Rufat Rufat - 1 month ago 6
C# Question

How to implement the default constructor (using constructor chaining) that sets the Category to Miscellaneous

I am very new to programming so I was trying to do some work with and got stuck with my problem.
Here is my code:

//Properties
private static readonly List<string> category = new List<string>
{
"Electric",
"Household",
"Garden",
"Miscellaneous"
};


Category HAS to be "readonly"

// Constructor
public Product(List<string> category)
{
// this.category shows error that it cannot be accessed with an instance reference;
// qualify it with a type name instead
this.category = category;
}


Also in the default constructor I cannot pass it

// Default Constructor
public Product() : this("Miscellaneous")
{
}


So, how to pass 1 one of strings within the list? Or should I use arrays for this? And how do I print it out later?

class TestProduct
{
static void Main(string[] args)
{
// Assigning correct properties to the product
Product p1 = new Product(1234567, "Cake", "Miscellaneous", 7.5, 150);
Console.WriteLine(p1);
Console.ReadLine();
}
}


Hope my question is clear.

apk apk
Answer

If you have a fixed set of categories, you can use an enum to store all values.

public enum ProductCategory
{
    Electric,
    Household,
    Garden,
    Miscellaneous
}

You can create a default constructor like this:

public enum ProductCategory
{
    Electric,
    Household,
    Garden,
    Miscellaneous
}

public class Product
{

    public ProductCategory Category { get; }

    public Product(ProductCategory category)
    {
        this.Category = category;
    }

    public Product() : this(ProductCategory.Miscellaneous)
    {
    }

}

static void Main()
{
    Product p1 = new Product();
    Console.WriteLine(p1.Category); // output: Miscellaneous
    Console.ReadKey();
}

If you still want to store your category in a string, you can adapt this example. If you want a fixed list of valid categories, you can check if the category is valid in the constructor.