Introduction
Generic methods let you write one method that works with different types, so you don't repeat code for each type.
public void MethodName<T>(T parameter) { // method body }
public void PrintItem<T>(T item) { Console.WriteLine(item); }
public T ReturnSame<T>(T value) { return value; }
public void Swap<T>(ref T a, ref T b) { T temp = a; a = b; b = temp; }
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); } }
<T>?PrintItem that takes one parameter of type T?public class Program {
public static void ShowType<T>(T value) {
Console.WriteLine(typeof(T));
}
public static void Main() {
ShowType(123);
ShowType("hello");
}
}public void Swap<T>(T a, T b) {
T temp = a;
a = b;
b = temp;
}FindMax that returns the maximum of two values of any type T. Which constraint should you add to T to make comparison possible?Pass the test and this pattern moves unknown