0
0
C Sharp (C#)programming~5 mins

Generic method declaration in C Sharp (C#)

Choose your learning style9 modes available
Introduction
Generic methods let you write one method that works with different types, so you don't repeat code for each type.
When you want a method to work with any data type, like numbers or text.
When you need to create reusable code that handles different kinds of objects.
When you want to avoid writing the same method multiple times for different types.
When you want to keep your code simple and flexible.
When you want to ensure type safety while using different data types.
Syntax
C Sharp (C#)
public void MethodName<T>(T parameter) {
    // method body
}
The after the method name declares a generic type parameter named T.
You can use T inside the method as a type for parameters, variables, or return type.
Examples
This method prints any item passed to it, no matter its type.
C Sharp (C#)
public void PrintItem<T>(T item) {
    Console.WriteLine(item);
}
This method returns the same value it receives, keeping the type.
C Sharp (C#)
public T ReturnSame<T>(T value) {
    return value;
}
This method swaps two variables of the same type.
C Sharp (C#)
public void Swap<T>(ref T a, ref T b) {
    T temp = a;
    a = b;
    b = temp;
}
Sample Program
This program defines a generic method PrintItem that prints any type of item. It is called with int, string, and double types.
C Sharp (C#)
using System;

class Program {
    public static void PrintItem<T>(T item) {
        Console.WriteLine($"Item: {item}");
    }

    static void Main() {
        PrintItem<int>(123);
        PrintItem<string>("hello");
        PrintItem<double>(3.14);
    }
}
OutputSuccess
Important Notes
You can name the generic type parameter anything, but T is common and easy to understand.
Generic methods help avoid errors by checking types at compile time.
You can have multiple generic parameters like if needed.
Summary
Generic methods let you write flexible code that works with many types.
Use <T> after the method name to declare a generic type parameter.
Generic methods improve code reuse and type safety.