Understanding Generics—Creating Generic Methods
Microsoft .NET Framework, ASP.NET, Visual C# (CSharp, C Sharp, C-Sharp) Developer Training, Visual Studio
Creating Generic Methods
To learn how to incorporate generics into your own projects, you’ll begin with a simple example of
a generic swap routine. The goal of this example is to build a swap method that can operate on any
possible data type (value-based or reference-based) using a single type parameter. Due to the nature
of swapping algorithms, the incoming parameters will be sent by reference (via the C# ref keyword).
Here is the full implementation:
// This method will swap any two items. // as specified by the type parameter <T>. static void Swap<T>(ref T a, ref T b) { Console.WriteLine("You sent the Swap() method a {0}", typeof(T)); T temp; temp = a; a = b; b = temp; }
Notice how a generic method is defined by specifying the type parameter after the method
name but before the parameter list. Here, you’re stating that the Swap() method can operate on any
two parameters of type <T>. Just to spice things up a bit, you’re printing out the type name of the
supplied placeholder to the console using the C# typeof() operator. Now ponder the following
Main() method that swaps integer and string types:
static void Main(string[] args) { Console.WriteLine("***** Fun with Generics *****\n"); // Swap 2 ints. int a = 10, b = 90; Console.WriteLine("Before swap: {0}, {1}", a, b); Swap<int>(ref a, ref b); Console.WriteLine("After swap: {0}, {1}", a, b); Console.WriteLine(); // Swap 2 strings. string s1 = "Hello", s2 = "There"; Console.WriteLine("Before swap: {0} {1}!", s1, s2); Swap<string>(ref s1, ref s2); Console.WriteLine("After swap: {0} {1}!", s1, s2); Console.ReadLine(); }
|

