I am going through a book trying to understand Generics with C# and I have come across an example I don’t understand. Here is the sample code.
using System;
public class Printer
{
public void Print<T>(T argument)
{
Console.WriteLine(argument.ToString());
}
static void Main(string[] arguments)
{
Printer printer = new Printer();
printer.Print<string>("Hello, World");
Console.WriteLine("Done");
Console.ReadKey();
}
}
What is confusing me is the argument to the Print method. I understand using a generic type placeholder when dealing with a collections such as List<T>. However what I don’t understand is how <T> comes into play with a method? Is the code just saying that the type of the parameter passed into the Print() method is just not known at design time and could be anything? Could someone help me decipher this? Thank you.
By declaring your method with a generic type, you make your method more flexible as it can then work with variables of any type you choose, including primitive types (unless you specify
where T : classof course).Another very common example that much better illustrates one use of a generic method is a
Swap<T>(T, T)method: