C# Collection Generic GenericCollection-Part 2
C# Collection Generic GenericCollection-Part 2
Generic programming in C# allows you to create classes, methods, interfaces, and other structures with
placeholders for the types they store or use. This provides several key benefits:
1. Type Safety: Generics ensure that you can only use the specified type, reducing runtime errors.
For example, a List<int> will only accept integers, preventing accidental addition of other types.
2. Reusability: You can write a single class or method that works with any data type. This reduces
code duplication and makes your code more maintainable. For instance, a generic list class can
store integers, strings, or any other type without needing separate implementations.
3. Performance: Generics can improve performance by eliminating the need for boxing and
unboxing when working with value types. This is because the type is specified at compile time,
allowing for more efficient code generation.
4. Flexibility: Generics allow you to create more flexible and reusable code. For example, you can
create a generic method that swaps two variables of any type:
C#
T temp = lhs;
lhs = rhs;
rhs = temp;
5. Consistency: Using generics helps maintain consistency across your codebase. For example,
the .NET collections library uses generics extensively, providing a consistent way to work with
different types of collections.
Generics are widely used in the .NET framework, especially in collections like List<T>, Dictionary<TKey,
TValue>, and Queue<T>, among others12.
Generic
Generics in C# allow you to define classes, methods, and interfaces with a placeholder for the type of
data they store or use. This makes your code more flexible and reusable. Let’s go through a simple
example to illustrate this.
C#
using System;
1. Generic Class Definition: The Box<T> class is defined with a type parameter T. This means T can
be any type (e.g., int, string, etc.).
2. Property: The Item property is of type T, so it can hold any type of data.
4. Instantiation: In the Main method, we create instances of Box for different types
(int and string).
Generic Method Example
C#
using System;
1. Generic Method Definition: The Print<T> method is defined with a type parameter T.
3. Method Call: In the Main method, we call Print with different types of arguments
(int and string).
Generics help you write more flexible and reusable code by allowing you to work with any data type
without sacrificing type safety12.
In C#, you can constrain a generic type using the where keyword. This allows you to specify certain
requirements that the type argument must meet. Here are some common constraints you can apply:
Types of Constraints
4. Base Class Constraint: Ensures the type is or derives from a specified base class.
C#
public class MyClass<T> where T : MyBaseClass
{
// T must be MyBaseClass or derived from MyBaseClass
}
Practical Example
Here’s a practical example that combines several constraints:
C#
using System;
In this example:
T must be a reference type (class), implement the IDisplayable interface, and have a
parameterless constructor (new()).
Constraints help ensure that the types used with your generics meet specific requirements, making your
code safer and more predictable
Arithmetical Operation on Generic
In C#, performing addition on generic types requires some additional considerations because operators
like + are not directly supported on generic types. However, with the introduction of .NET 7 and C# 11,
you can use the new generic math interfaces to achieve this.
Here’s how you can use the + operator on a generic type by leveraging the INumber<T> interface:
1. Define a Generic Method with Constraints: Use the INumber<T> interface to constrain your
generic type to numeric types.
2. Implement the Addition: Use the + operator within the method.
Here’s an example:
C#
using System.Numerics;
class Program
{
static void Main()
{
int resultInt = MathOperations.Add(3, 5);
double resultDouble = MathOperations.Add(2.5, 4.3);
Generic Collections work on the specific type that is specified in the program whereas non-generic
collections work on the object type.
a. Specific type
b. Array Size is not fixed
c. Elements can be added / removed at runtime.
C# List
1. using System.Collections.Generic;
2.
3. protected void Button1_Click(object sender, EventArgs e)
4. {
5. List<int> lst = new List<int>();
6. lst.Add(100);
7. lst.Add(200);
8. lst.Add(300);
9. lst.Add(400);
10. foreach (int i in lst)
11. {
12. Response.Write(i+"<br>");
13. }
14. }
C# Dictonary
1. using System.Collections.Generic;
2.
3. protected void Button1_Click(object sender, EventArgs e)
4. {
5. Dictionary<int, string> dct = new Dictionary<int, string>();
6. dct.Add(1, "cs.net");
7. dct.Add(2, "vb.net");
8. dct.Add(3, "vb.net");
9. dct.Add(4, "vb.net");
10. foreach (KeyValuePair<int, string> kvp in dct)
11. {
12. Response.Write(kvp.Key + " " + kvp.Value);
13. Response.Write("<br>");
14. }
15. }
C# SortedList
1. using System.Collections.Generic;
2.
C# Stack
1. using System.Collections.Generic;
2.
C# Queue
1. using System.Collections.Generic;