CSharp: How to declare a generic function

From /etc/src/
Jump to: navigation, search

Description

This code sample demonstrates how to declare a generic function using the C# programming language.

Prerequisites

  • C# compiler with any standard ASCII editor like Notepad, or
  • Visual Studio Express with C# compiler, or
  • Visual Studio.Net or better with C# compiler.

Code

 1 using System;
 2  
 3 class Program {
 4     static void Print<T> (T obj) {
 5         Console.WriteLine (obj);
 6     }
 7  
 8     static void Main (string[] args) {
 9         Print ("Hello, world");
10         Print (3.1415);
11         Print ('X');
12     }
13 }

Output

Hello, world
3.1415
X

Explanation

The code listing above shows a simple function, Print() that is defined for a generic type, which we define simply as T. This function becomes a placeholder of sorts for any function that will call it with a particular type. For example, in the Main() function, we call the Print() function with three different constants: a string ("Hello, world"); a double (3.1415); and a char ('X'). In all of these cases the call to Print() is resolved to the correct "copy" of the Print() function.

Additional notes

In the code above we called the Print() function directly with a particular type without having to tell the compiler about the type instance to call. We can, however, be explicit while making a call to the templatized generic type. Have a look at the code below.

Code

 1 using System;
 2  
 3 class Program {
 4     static void Print<T> (T obj) {
 5         Console.WriteLine (obj);
 6     }
 7  
 8     static void Main (string[] args) {
 9         Print<string> ("Hello, world");
10         Print<double> (3.1415);
11         Print<char> ('X');
12     }
13 }

The output is the same as the previous code listing.

References

See also

Further reading

External links

Author link