Member-only story
Generics in C# with Examples
Generics in C# provide a way to define classes, interfaces, methods, and delegates with placeholder types. These placeholder types, called type parameters, can then be replaced with actual types when instances of generic types are created or when generic methods are invoked. Generics enable you to write more flexible and reusable code by allowing you to create components that can work with any data type.
The FruitList class:
- It has a private array _fruitItems of type T[] to store the elements.
2. It has a private integer _count to keep track of the number of elements in the list.
3. It has a constructor that initializes the _fruitItems array with a specified capacity and sets _count to 0.
4. It has an Add method to add elements to the list. The method takes an item of type T as a parameter, assigns it to the next available index in the _fruitItems array, and increments _count.
5. It has a Get method to retrieve an element from the list at a specified index. It returns the element at the specified index in the _fruitItems array.
The Main method:
- It creates an instance of FruitList named priceList to store integers with a capacity of 5.