For moer details, see this article
http://msdn2.microsoft.com/en-us/library/512aeb7t(vs.80).aspx
C#
// Declare the generic class
public class GenericList
{
void Add(T input) { }
}
class TestGenericList
{
private class ExampleClass { }
static void Main()
{
// Declare a list of type int
GenericList
// Declare a list of type string
GenericList
// Declare a list of type ExampleClass
GenericList
}
}
MORE DETAILS
Generics introduce to the .NET Framework the concept of type parameters, which make it possible to design classes and methods that defer the specification of one or more types until the class or method is declared and instantiated by client code. For example, by using a generic type parameter T you can write a single class that other client code can use without incurring the cost or risk of runtime casts or boxing operations
Remember Boxing and unboxing when come across geenrics
create your own generic interfaces, classes, methods, events and delegates
The data type of the parameters can change with each use
Sample method using Generic DataType
protected GenType MyMethod
{
return item;
}
Example
// This method will swap any two items.
// as specified by the type parameter
static void Swap
{
Console.WriteLine("You sent the Swap() method a {0}",
typeof(T));
T temp;
temp = a;
a = b;
b = temp;
}
Generics provide a way for programmers to define “placeholders” (formally termed type parameters) for method arguments and type definitions, which are specified at the time of invoking the generic method or creating the generic type.
By convention, generic types specify their placeholders using uppercase letters. Although any letter (or word) will do, typically T is used to represent types, K is used for keys, and V is used for values.
.NET generics may be defined with optional constraints using the where keyword to address issues like Cannot convert type T to..given that the compiler does not yet know the value of the type parameter
Example:-
where T : struct The type parameter
where T : class The type parameter
// Contained items must have a default ctor.
public class MyGenericClass
{...}
// Contained items must be a class implementing IDrawable
// and support a default ctor.
public class MyGenericClass
{...}
// MyGenericClass derives from MyBase and implements ISomeInterface,
// while the contained items must be structures.
public class MyGenericClass
{...}
(http://en.csharp-online.net/Understanding_Generics%E2%80%94Constraining_Type_Parameters_Using_where)
No comments:
Post a Comment