www.pickatutorial.com Computer Tutorials
Top eBooks: C/C++ | C# | Android | Mathematics | Database | Cloud | Graphics | Networking | Oracle | Hardware | AI
Top Tutorials: C/C++ | C#.NET | PHP MySQL | Java | Java Script | jQuery | HTML | xHTML | HTML5 | VB Script| CSS
Lessons C# Generics Bookmark and Share
Tutorial Home
Lesson 1
Lesson 2
Lesson 3
Lesson 4
Lesson 5
Lesson 6
Lesson 7
Lesson 8
Lesson 9
Lesson 10
Lesson 11
Lesson 12
Lesson 13
Lesson 14
Lesson 15
Lesson 16
Lesson 17
Lesson 18
Lesson 19
Lesson 20
Lesson 21
Lesson 22
Lesson 23
Both Java and C++ have the feature of Generics. In C# it is no different. Generics is essentially the ability to have type parameters on our own defined types. They are also called parameterized types. .NET’s System.Collections.Generic namespace has a number of useful generic classes available for our use.

The following example illustrates the use of generics in C#:
 public class GenericContainer <T>
   private T element; 
   public GenericContainer(T element) 
      this.element =element; 
   public T getElement() 
      return this.element;  
The instantiation of objects from the above GenericContainer class is pretty simple:

GenericContainer<int> a = new GenericContainer<int>(34);
// Generic Container of int type

GenericContainer<string> a = new GenericContainer<string>(“Hello World”);
// Generic Container of string type

GenericContainer<double> a = new GenericContainer<double>(3.04);
// Generic Container of double type

From the above GenericContainer class you could instantiate any number of containers, each having the capability to store a different type of element. While the example is far from practical, it does illustrate the basic idea of generics.

Note that you can have any number of type parameters in a generic class as per your needs. Each additional type parameter has to have a different name. We used T in the above example and if we needed to have an additional type parameter we could have named it as S, for example.
Next >>> Lesson No. 20: C# Interfaces, Boxing, new

Home - Advertise - Contact - Disclaimer - About Us
© Since 2006 pickatutorial.com -- All Rights Reserved.