C# Generics – An Introduction
There is a reality; most of the developers confuse about C# Generics. Actually, there is no reason for that. If your background comes from C++ or Java you may understand more easily. Wha t tell you from your C++ knowledge o r from Java. Main concept is same here in C# with some better extensions and easy usability. For example since C++ Templates uses compile time, C# Generics also a feature of the runtime. They are basically the capacity to have type parameters lying on your type. Generics refer to classes and methods that work homogeneously on values of different types. They are a type of data structure that contains code that remains the same; though, the data type of the parameters can change with each use. We can also call them parameterized types or parametric polymorphism.
The usage of generics within the data structure adjusts to the different data type of the passed variables. Briefly, a generic is a code template that can be applied to use the same code over and over again. Whenever the generic is used, it can be adapted for different data types without require to rewrite any of the internal code.
A List collection class can be a good example:
List<int> Mylist1 = new List<int>();
// No boxing or casting necessary
list1.Add (5);
If we want to expand this code and make it more sensible, we can build
something like this:
using System;
using System.Collections;
using System.Text;
namespace TList
{
public class List<template> : CollectionBase
{
public List(){ }
public Template this[int index]
{
get { return (Template)List[index]; }
set { List[index] = value; }
}
public int Add(Template value)
{
return List.Add(value);
}
}
}
</template></int></int>
If we decide to convert any fields to generic fields, we would just change their types to Template. Continues…
Pages: 1 2












No comments yet... Be the first to leave a reply!