Skip to content

Generics

Generic Method Argument Types

Methods in C# can be generic, which means they can work with different types without the need to write separate methods for each type.

The types specified in the angle brackets <> are placeholders that get replaced with actual types when the method is called.

public class GenericExample
{
    public T FindMax<T>(T first, T second) 
    where T : IComparable<T>
    {
        return first.CompareTo(second) > 0 ? first : second;
    }
}

class Program
{
    static void Main(string[] args)
    {
        GenericExample example = new GenericExample();

        // Using with integers
        int maxInt = example.FindMax(10, 20);
        // Output: Max integer: 20
        Console.WriteLine($"Max integer: {maxInt}"); 

        // Using with doubles
        double maxDouble = example.FindMax(3.14, 2.71);
        // Output: Max double: 3.14
        Console.WriteLine($"Max double: {maxDouble}"); 

        // Using with strings
        string maxString = example.FindMax("apple", "banana");
        // Output: Max string: banana
        Console.WriteLine($"Max string: {maxString}"); 
    }
}

More info: https://www.perplexity.ai/search/explain-this-c-code-return-bui-VfKldz9uR5Kt2Yl7rZDHmQ