C# Generic Methods

In this chapter you will learn:

  1. What are Generic Methods
  2. Example generic method

Description

A generic method declares type parameters within the signature of a method.

With generic methods, many algorithms can be implemented in a general-purpose way.

Example

Here is a generic method that swaps two values of any type:


static void Swap<T> (ref T a, ref T b)
{// w  ww.  j a  v  a  2 s. c  om
 T temp = a;
 a = b;
 b = temp;
}

Swap<T> can be used as follows:


int x = 5;
int y = 10;
Swap (ref x, ref y);

Next chapter...

What you will learn in the next chapter:

  1. What is default Generic Value
  2. Example for default Generic Value
Home »
  C# Tutorial »
    C# Types »
      C# Generics
C# Generic Types
C# Generic Methods
C# default Generic Value
C# Generic Constraints
C# Subclassing Generic Types
C# Generic Delegate
C# Type Parameters