Reputation: 348
Currently, I am accessing the property by creating a static method like the one below.
public static class CartCollection : List<Cart>
{
public static void Add(Cart Cart)
{
Add(Cart);
}
}
All I am trying to achieve is to have access to all the properties of List<>.
Outside of the class, I'd like to be able to do the following:
Cart cart = new Cart();
cart.SomeProperty = 0;
CartCollection.Add(cart);
Thanks!
Upvotes: 0
Views: 248
Reputation: 27894
Why subclass List at all? If you're not adding additional functionality, why not just use List<Cart>
?
public static class CartCollection
{
public static readonly List<Cart> Instance = new List<Cart>();
}
Cart cart = new Cart();
cart.SomeProperty = 0;
CartCollection.Instance.Add(cart);
Upvotes: 0
Reputation: 273854
Don't inherit from List<>
, embed one:
public static class CartCollection
{
private static List<Cart> _list = new List<Cart>();
public static void Add(Cart Cart)
{
_list.Add(Cart);
}
}
Upvotes: 0
Reputation: 169478
Two things:
1) Don't inherit List<T>
. Implement IList<T>
.
2) Use a singleton:
public class CartCollection : IList<Cart>
{
public static readonly CartCollection Instance = new CartCollection();
private CartCollection() { }
// Implement IList<T> here
}
Also, as you are using this in an ASP.NET app, you should know that static members are shared by all requests. Using this kind of code without lock
ing appropriately may lead to crashes. And even if you use lock
, you will share data between your users, which you may not want...
Upvotes: 1