Reputation: 1179
I have 3 classes (A
,B
,C
) and have to implement a storing method for all of the classes so I thought that of using a generic list like List<T> = new List<T>();
but it doesn't allow me to use it.
I would like the method to be like this:
class Bascket
{
List<T> list= new List<T>();
public void addToBasket(T value)
{
list.Add(value);
}
}
Upvotes: 0
Views: 2485
Reputation: 6911
Assuming that A, B and C are items which you wish to store in the Basket object, you should create a base class of those items, and declare generic collection as collection of base class, i.e.
public interface IBasketItem
{
/* put some common properties and methods here */
public decimal Price { get; set; }
public string Name { get; set; }
}
public class A : IBasketItem
{ /* A fields */ }
public class B : IBasketItem
{ /* B fields */ }
public class C : IBasketItem
{ /* C fields */ }
public class Basket
{
private List<IBasketItem> _items = new List<IBasketItem>();
public void Add(IBasketItem item)
{
_items.Add(item);
}
public IBasketItem Get(string name)
{
// find and return an item
}
}
You can then use Basket class to store all your items.
Basket basket = new Basket();
A item1 = new A();
B item2 = new B();
C item3 = new C();
basket.Add(item1);
basket.Add(item2);
basket.Add(item3);
However, when retrieving items back, you should use common interface, or you should know of which type the object actually is. E.g:
IBasketItem myItem = basket.Get("cheese");
Console.WriteLine(myItem.Name);
// Take care, if you can't be 100% sure of which type returned item will be
// don't cast. If you cast to a wrong type, your application will crash.
A myOtherItem = (A)basket.Get("milk");
Console.WriteLine(myOtherItem.ExpiryDate);
Upvotes: 3
Reputation: 58962
The problem is that T
is not declared. You can add a generic parameter to your class for this to work:
class Basket<T>
{
List<T> list= new List<T>();
public void addToBasket(T value)
{
list.Add(value);
}
}
This allows you to use your class like this:
var basket = new Basket<string>();
basket.addToBasket("foo"); // OK
basket.addToBasket(1); // Fail, int !== string
Upvotes: 2