|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
|
Announcements
Want a new Job?
Chapters
Services
Feature Zones
|
IntroductionWe 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. 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<int> list = new MyCustomList<int>();
// Add two integers to listlist.Add(1);
list.Add(33);
// The next statement will fail and wont compile
list.Add("Emp");
If we want our 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. public class MySecondCustomList<myType,mySecondType>
{...}
So far so good. ConstraintsNow, 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 public class MyCustomList<myType>
where myType : IDisposable
{ ... }
If there are more than one constraints, we can separate it by commas. E.g.: 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.: public myType MyGenericFunction<myType>(myType item)
{
........
return item;
}
ConclusionIn 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. HistoryVersion 1.0
|
|||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||