ValueTuple as Type Parameter of Generic Method
A generic method can receive ValueTuple as its type parameter.
class Demo
{
static void Print<T>(T value)
{
Console.WriteLine(value);
}
static void Main()
{
Print<(string, int)>(("Ajeet", 25));
}
}
Output
(Ajeet, 25)
Generic Method returning ValueTuple
class Demo
{
static T Echo<T>(T value)
{
return value;
}
static void Main()
{
var result = Echo<(string Name, double Marks)>(("Ajeet", 91.5));
Console.WriteLine(result.Name);
Console.WriteLine(result.Marks);
}
}
Output
Ajeet
91.5
Generic Method with Type Inference
Type argument often does not need to be written explicitly:
class Demo
{
static void Show<T>(T data)
{
Console.WriteLine(data);
}
static void Main()
{
Show(("Delhi", 28));
}
}
Here T is automatically inferred as: (string, int)
So ValueTuple works like any other type in generics.
No comments:
Post a Comment