Junior
Is it possible to use more than one template type in C#?
sobes.tech AI
Answer from AI
Yes, it is possible to use multiple generic types in C#. This allows creating more flexible generic classes and methods.
// Example of a generic class with two generic types
public class Pair<TKey, TValue>
{
public TKey Key { get; set; }
public TValue Value { get; set; }
// Constructor
public Pair(TKey key, TValue value)
{
Key = key;
Value = value;
}
}
// Example of a generic method with two generic types
public TResult Merge<TFirst, TSecond, TResult>(TFirst first, TSecond second, Func<TFirst, TSecond, TResult> merger)
{
// The method combines two values using the provided function
return merger(first, second);
}
In the class Pair<TKey, TValue>, TKey and TValue are independent generic types. They can be any data types when creating an instance of the class.
In the method Merge<TFirst, TSecond, TResult>, three generic types are used: TFirst, TSecond, and TResult. TResult defines the return type of the method, while TFirst and TSecond are the types of the input parameters.
This is a fundamental feature of generics, widely used in the .NET Framework and .NET Core for creating collections (e.g., Dictionary<TKey, TValue>), delegates, and other flexible structures.