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

Multiple generic parameters in C Sharp (C#)

Choose your learning style9 modes available
Introduction

Using multiple generic parameters lets you create flexible code that works with different types at the same time.

When you want a class or method to handle two or more different types safely.
When you need to pair two types together, like a key and a value.
When writing reusable code that can work with many type combinations.
When you want to avoid writing the same code for different type pairs.
When creating data structures like dictionaries or tuples.
Syntax
C Sharp (C#)
class ClassName<T1, T2> {
    // Use T1 and T2 inside
}

void MethodName<T1, T2>(T1 param1, T2 param2) {
    // Use param1 and param2
}

Each generic parameter is separated by a comma inside angle brackets <>.

You can use as many generic parameters as you need.

Examples
This class stores two values of different types together.
C Sharp (C#)
class Pair<T1, T2> {
    public T1 First;
    public T2 Second;

    public Pair(T1 first, T2 second) {
        First = first;
        Second = second;
    }
}
This method prints two values of any types.
C Sharp (C#)
void PrintPair<T1, T2>(T1 a, T2 b) {
    Console.WriteLine($"First: {a}, Second: {b}");
}
Creating a Pair with an int and a string, then printing them.
C Sharp (C#)
var pair = new Pair<int, string>(10, "apples");
Console.WriteLine($"{pair.First} {pair.Second}");
Sample Program

This program shows a class with two generic types and a method with two generic types. It creates a pair and prints it, then calls the method with different types.

C Sharp (C#)
using System;

class Pair<T1, T2> {
    public T1 First;
    public T2 Second;

    public Pair(T1 first, T2 second) {
        First = first;
        Second = second;
    }
}

class Program {
    static void PrintPair<T1, T2>(T1 a, T2 b) {
        Console.WriteLine($"First: {a}, Second: {b}");
    }

    static void Main() {
        var pair = new Pair<int, string>(5, "oranges");
        Console.WriteLine($"Pair contains: {pair.First} and {pair.Second}");

        PrintPair<double, bool>(3.14, true);
    }
}
OutputSuccess
Important Notes

Generic parameters can have constraints to limit what types are allowed.

Using multiple generics helps keep code safe and reusable.

Summary

Multiple generic parameters let you work with many types at once.

They make your code flexible and reusable.

You separate generic types with commas inside <>.