C# Tutorial
C# String
C# Array
C# Flow Control
C# Class and Object
C# Inheritance
C# Interface
C# Collection
C# Generic
C# File I/O
C# Delegate and Event
C# Exception
C# Process and Thread
C# ADO.NET Database Operations
In this tutorial, we will explore generic methods in C#. Generic methods are methods that have one or more type parameters, allowing you to create more flexible, reusable, and type-safe code.
To define a generic method, you include the type parameters inside angle brackets <T>
after the method name, where T
is a placeholder for the actual type you will use later.
Here's a simple example of a generic method called PrintArray
:
public static void PrintArray<T>(T[] array) { foreach (T item in array) { Console.Write(item + " "); } Console.WriteLine(); }
In this example, T
is a type parameter that represents the type of the elements in the array
parameter.
When calling a generic method, the compiler usually infers the type parameters based on the method arguments. For example, you can call the PrintArray
method with different types of arrays:
int[] intArray = { 1, 2, 3 }; string[] stringArray = { "Hello", "World" }; PrintArray(intArray); // Output: 1 2 3 PrintArray(stringArray); // Output: Hello World
If the compiler cannot infer the type parameters, you can explicitly specify them using angle brackets:
PrintArray<int>(intArray);
You can add constraints to type parameters to restrict the types that can be used with the generic method. Constraints are specified using the where
keyword followed by the type parameter, a colon, and the constraint.
For example, you can define a generic method to compare two objects of a type that implements IComparable<T>
:
public static T Max<T>(T a, T b) where T : IComparable<T> { return a.CompareTo(b) > 0 ? a : b; }
In this example, the constraint where T : IComparable<T>
ensures that the type T
implements the IComparable<T>
interface, allowing you to call the CompareTo
method.
You can use the Max
method with types that implement IComparable<T>
:
int maxInt = Max(5, 10); // 10 string maxString = Max("apple", "banana"); // "banana"
You can define generic methods within generic classes. The method's type parameters can be different from or extend the class's type parameters. Here's an example of a generic method inside a generic class:
public class Container<T> { private List<T> _items = new List<T>(); public void Add(T item) { _items.Add(item); } public void AddRange<U>(IEnumerable<U> items) where U : T { _items.AddRange(items); } }
In this example, the AddRange
method has a different type parameter U
that is constrained to be a subtype of T
. This allows you to add a range of items to the container as long as they are of the same type or a derived type of T
.
This tutorial demonstrates the basics of defining and using generic methods in C#. Generics are a powerful feature that enables you to create more flexible and reusable code, while preserving type safety.
How to define generic methods in C#:
public class GenericMethods { public T Display<T>(T value) { Console.WriteLine(value); return value; } }
C# generic method example:
class Program { static void Main() { GenericMethods genericMethods = new GenericMethods(); int intValue = genericMethods.Display(42); string stringValue = genericMethods.Display("C# Generics"); } }
Type inference in C# generic methods:
var inferredValue = genericMethods.Display("Inferred Type");
C# generic method constraints:
public T CompareTo<T>(T value) where T : IComparable<T> { // Implementation for comparing values }
Overloading with generic methods in C#:
public T Sum<T>(T a, T b) { // Implementation for summing values of the same type } public string Sum(string a, string b) { // Implementation for concatenating strings }
C# extension methods with generics:
public static class StringExtensions { public static bool IsNullOrEmpty<T>(this T input) { // Implementation for checking if the input is null or empty } }
Generic method with multiple type parameters in C#:
public void DisplayPair<TFirst, TSecond>(TFirst first, TSecond second) { Console.WriteLine($"{first}, {second}"); }