Generics

Generics

Chapter 11: Generics

Generics in C# are a powerful feature that allows you to define type-safe data structures, without committing to actual data types. Generics lead to more reusable, efficient, and type-safe code.

Why Generics?

Generics were added to provide a mechanism for defining and using generic types. Before generics, you could write a method that takes an object, but then you lose type safety, or you could write a separate method for each type you want to handle, but that leads to a lot of duplicate code.

With generics, you can write a single method that can handle different types in a type-safe manner.

Defining and Using Generic Types

Here's an example of how to define a generic class:

Không có mô tả.

In this example, T is a type parameter. You can use T as a type in the MyGenericClass class, and when you create an instance of MyGenericClass, you replace T with an actual type:

MyGenericClass<int> myClass = new MyGenericClass<int>(10);

int value = myClass.GenericMethod(5); // Outputs "Parameter type: System.Int32, parameter value: 5, member value: 10"

Generic Constraints

Generics in C#: A Comprehensive Guide with Code Examples and Explanations

C# allows you to limit the types that can be used with a generic class or method. These are known as generic constraints.

Here's an example of a generic class with a constraint:

public class MyGenericClass where T : IComparable { // ... }


In this example, the where T : IComparable constraint means that T must be a type that implements the IComparable interface.

For video tutorials on generics in C#:

Complete and Continue