Reputation: 121
I have the following class in which I have an IEnumerable
list as follows
public class Orders
{
public string No { get; set; }
public string Id { get; set; }
public IEnumerable<string> OrderTypes { get; set; } = new List<string> { "order 1", "order 2", "order 3" }
}
Instead of me assigning the values directly above is there a way i can put it in a separate class as follows
public class OrderTypes()
{
IEnumerable<string> myEnumerable = new List<string>()
myEnumerable.add("Order 1")
myEnumerable.add("Order 3")
myEnumerable.add("Order 4")
myEnumerable.add("Order 5")
myEnumerable.add("Order 6")
}
And then call this function above like
public class Orders
{
public string No { get; set; }
public string Id { get; set; }
public IEnumerable<string> OrderTypes { get; set; } = OrderTypes
}
The reason for this is cause my list gets too long and it would be easier to view, but I'm not sure how to achieve this.
Upvotes: 0
Views: 570
Reputation: 265231
Close enough. You can simply use a static method:
public class Orders
{
public string No {get;set;}
public string Id {get;set;}
public IEnumerable<string> OrderTypes{get;set;} = CreateOrderTypes();
private static IEnumerable<string> CreateOrderTypes()
{
return new List<string>
{
"Order 1",
"Order 3",
"Order 4",
"Order 5",
"Order 6",
};
}
}
Of course, the CreateOrderTypes
does not have to be in the same class and can be moved to a different class. The second class has to be visible to the first one.
public class Orders
{
public string No {get;set;}
public string Id {get;set;}
public IEnumerable<string> OrderTypes{get;set;} = OrderTypesFactory.InitOrderTypes();
}
static class OrderTypesFactory
{
static IEnumerable<string> InitOrderTypes()
{
return new List<string>
{
"Order 1",
"Order 3",
"Order 4",
"Order 5",
"Order 6",
};
}
}
Upvotes: 3
Reputation: 748
If I understand the question correctly, you could have a constructor for class Orders
and then when you instantiate the class, you could pass a value of IEnumerable inside it and assign that value. So it would look something like:
public class Orders
{
public string No { get; set; }
public string Id { get; set; }
public IEnumerable<string> OrderTypes { get; set; }
public Orders(IEnumerable<string> orderTypes)
{
OrderTypes = orderTypes;
}
}
public class Main
{
public void Main()
{
var orderTypes = new List<string>() { "Your", "values", "Here" };
var orders = new Orders(orderTypes);
}
}
Upvotes: 1