I have the following code, The problem is when I’m trying to assign the country to customer, getting error. I need to know how to assign the property that is declared as enum? I will use this in a linq expression, is there any other way to use enum?
var customers = new Customer[] {
new Customer { Name= "Badhon",City= "Dhaka",Country=Countries.Country.Bangladesh,Order= new Orders[] {
new Orders { OrderID=1,ProductID=1,Quantity=2,Shipped=false,Month="Jan"}}},
new Customer {Name = "Tasnuva",City = "Mirpur",Country =Countries .Country .Italy,Order =new Orders[] {
new Orders { OrderID=2,ProductID=2,Quantity=5,Shipped=false,Month="Feb"}}}
}
My enum is defined like this:
public class Countries
{
public enum Country {Italy,Japan,Bangladesh};
}
And Customer as follows:
public class Customer
{
public string Name;
public string City;
public Countries Country;
public Orders[] Order;
public override string ToString()
{
return string.Format("Name: {0} - City: {1} - Country: {2}", this.Name, this.City, this.Country);
}
}
Your problem is that your field in Customer is of type
Countries, notCountries.Country. And you are trying to assign aCountries.Countrywhich obviously is incompatible.An enum is a type, just like classes are. You don’t need the class around it. You should get rid of the outer class there:
and redefine the field in
Customer:(yes, having a class member with the same name as a type works in C#).
Another issue: You should probably use properties and not fields:
This will make your life easier down the line (and you can use it just like you did now, until you have read up on the differences).