Friday, June 19, 2026

C# Example of ValueTuple as Type Argument of Generic Class

ValueTuple as Type Parameter of Generic Class: You can supply a ValueTuple as the type argument to a generic class.

Example: List<T> with ValueTuple

class Demo
{
    static void Main()
    {
        List<(string Name, int Age)> students = 
            new List<(string Name, int Age)>(); students.Add(("Ajeet", 25));
        students.Add(("Rahul", 30));
        foreach (var s in students)
        {
            Console.WriteLine($"{s.Name} - {s.Age}");
        }
    }
}

Output

Ajeet - 25

Rahul - 30

Example: Custom Generic Class

class Container<T>
{
    public T Data { get; set; }
}
class Demo
{
    static void Main()
    {
        Container<(string City, int Population)> obj = 
            new Container<(string City, int Population)>();
        obj.Data = ("Delhi", 32000000);
        Console.WriteLine(obj.Data.City);
        Console.WriteLine(obj.Data.Population);
    }
}

Output

Delhi32000000

No comments:

Post a Comment

Hot Topics