Click here to Skip to main content
15,881,455 members
Articles / Programming Languages / C#
Article

Generics in C# 2.0

Rate me:
Please Sign up or sign in to vote.
3.05/5 (40 votes)
23 Sep 20042 min read 188.9K   46   10
An introduction to Generics in C#.

Introduction

We are going to take a look at a new cool feature of C# 2.0. It is not constrained to C# but also available with other .NET languages.

As the projects get more complicated, programmers increasingly need a means to better reuse and customize their existing component-based software. To achieve such a high level of code reuse in other languages, programmers typically employ a feature called Generics. Using Generics, we can create class templates that support any type. When we instantiate that class, we specify the type we want to use, and from that point on, our object is "locked in" to the type we chose.

Let us look at an example of how we can create a generic class using C# 2.0.

C#
public class MyCustomList<MYTYPE> 
{
  private ArrayList m_list = new ArrayList(); 
  public int Add(myType value)
  {
    return m_list.Add(value);
  } 

  public void Remove(myType value)
  {
    m_list.Remove(value);
  } 

  public myType this[int index]
  {
    get
    {
      return (myType)m_list[index];
    }
    set
    {
      m_list[index] = value;
    }
  }
}

Here, MyCustomList is built on an ArrayList. But its methods and indexer are strongly typed. Here <myType> is really just a placeholder for whatever type you choose when you create the class. This placeholder is defined in angled brackets after the name of the class. Now, let us look at how to create an instance of the class MyCustomList:

C#
MyCustomList<int> list = new MyCustomList<int>();
// Add two integers to list
C#
list.Add(1);
list.Add(33);
// The next statement will fail and wont compile
list.Add("Emp");

If we want our MyCustomList to store strings, it can be done as follows:

C#
MyCustomList<string> list = new MyCustomList<string>();

We can have multiple types in our base template class. Just separate each type with a comma in between the angular brackets.

C#
public class MySecondCustomList<myType,mySecondType>
{...}

So far so good.

Constraints

Now, we will look at applying constraints by which we can restrict what types are allowed. For e.g., if we want to restrict our type to only the types implementing IDisposable interface, we can do it as follows:

C#
public class MyCustomList<myType>
  where myType : IDisposable
{ ... }

If there are more than one constraints, we can separate it by commas. E.g.:

C#
public class MyDictionary<KeyType, ValType> where
KeyType : IComparable,
KeyType : IEnumerable

Generics are not limited to classes. They can also be used in structures, interfaces, and delegates. We can even use generics to parameterize a method by type. E.g.:

C#
public myType MyGenericFunction<myType>(myType item)
{
  ........
  return item;
}

Conclusion

In general, Generics allow programmers to author, test, and deploy code once, and then reuse that code for a variety of different data types. In addition, generics are checked at compile-time. When your program instantiates a generic class with a supplied type parameter, the type parameter can only be of the type your program specified in the class definition.

History

Version 1.0

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here


Written By
Software Developer (Senior)
India India
Just another Developer
http://anzboy.wordpress.com/

Comments and Discussions

 
GeneralMy vote of 5 Pin
Member 1067543018-Mar-14 0:58
Member 1067543018-Mar-14 0:58 
GeneralMy vote of 5 Pin
Renju Vinod31-Jul-13 18:50
professionalRenju Vinod31-Jul-13 18:50 
GeneralMy vote of 4 Pin
masbaaz20-Sep-12 9:52
masbaaz20-Sep-12 9:52 
GeneralMy vote of 4 Pin
Amir Hossein Jamshidi9-May-12 7:04
Amir Hossein Jamshidi9-May-12 7:04 
GeneralMy vote of 5 Pin
llcutealill10-Jan-12 12:23
llcutealill10-Jan-12 12:23 
Questiontype o? Pin
Phillip Holmes8-Sep-06 2:55
Phillip Holmes8-Sep-06 2:55 
AnswerRe: type o? Pin
Eytukan2-Feb-09 5:26
Eytukan2-Feb-09 5:26 
GeneralThe list (in System.Collections.Generic) already does it! Pin
Evandrojr5-Nov-04 9:43
Evandrojr5-Nov-04 9:43 
The List is like an arrayList for generics

And does it better!;P
GeneralIncorrect comment Pin
Heath Stewart23-Sep-04 5:29
protectorHeath Stewart23-Sep-04 5:29 
GeneralRe: Incorrect comment Pin
Ansil23-Sep-04 17:38
Ansil23-Sep-04 17:38 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.