Swiftorial Logo
Home
Swift Lessons
Tutorials
Learn More
Career
Resources

Generics

Introduction to Generics

Generics in .NET allow you to write reusable code that can work with different data types while maintaining type safety. They are widely used in collections and algorithms.

Generic Classes

You can define classes, structs, interfaces, delegates, and methods with placeholders for the data type.

Example: Generic Class


public class MyGenericClass<T> {
    public T Data { get; set; }

    public void DisplayData() {
        Console.WriteLine($"Data: {Data}");
    }
}
    

Usage:


var myInt = new MyGenericClass<int>();
myInt.Data = 10;
myInt.DisplayData(); // Output: Data: 10

var myString = new MyGenericClass<string>();
myString.Data = "Hello, Generics!";
myString.DisplayData(); // Output: Data: Hello, Generics!
    

Generic Methods

Methods can also be generic, allowing you to define methods that operate on specific data types determined at runtime.

Example: Generic Method


public T FindMax<T>(T[] array) where T : IComparable<T> {
    T max = array[0];
    foreach (T item in array) {
        if (item.CompareTo(max) > 0) {
            max = item;
        }
    }
    return max;
}
    

Usage:


int[] intArray = { 3, 7, 1, 5, 9 };
Console.WriteLine(FindMax(intArray)); // Output: 9

string[] stringArray = { "apple", "orange", "banana" };
Console.WriteLine(FindMax(stringArray)); // Output: orange
    

Constraints with Generics

You can apply constraints to generics to restrict the types that can be used as arguments.

Example: Generic Constraint


public class MyGenericClass<T> where T : IComparable<T> {
    // Class definition with constraint
}
    

Benefits of Generics

  • Type safety
  • Code reuse
  • Performance optimizations

Conclusion

Generics are a powerful feature in .NET that enhance code readability, reusability, and type safety. They are widely used in creating flexible and efficient data structures and algorithms.