Generics is a concept introduced in .NET 2.0 and these are
just like templates in C++. Using generics we can create
classes,methods,events, delegates which work with any type
(like int,string,myclass etc). In .NET 2.0,
System.Collections.Generic namesapce was introduced and it
contains classes/interfaces related to generics. Advantages
are Performance, Code Reuse, Type Safety.
Generic helps us to maximize the reuse of code, Type safety and better performance. Generics are most commonly used to create a collection. There are many new generic collection classes in the System.collection.Generics namespace. These classes are advised to be used for type safety and better performance over araylist.
We can also create our own Generic interface, classes, methods, events and delegates. Information on the types used in a generic data type may be obtained at run-time by means of reflection
Example:
class GenericMethod
{
static void Main( string[] args )
{
// create arrays of int, double and char
int[] intArray = { 1, 2, 3, 4, 5, 6 };
double[] doubleArray = { 1.1, 2.2, 3.3, 4.4, 5.5, 6.6, 7.7 };
char[] charArray = { 'H', 'E', 'L', 'L', 'O' };
Console.WriteLine( "Array intArray contains:" );
PrintArray( intArray ); // pass an int array argument
Console.WriteLine( "Array doubleArray contains:" );
PrintArray( doubleArray ); // pass a double array argument
Console.WriteLine( "Array charArray contains:" );
PrintArray( charArray ); // pass a char array argument
} // end Main
// output array of all types
static void PrintArray< E >( E[] inputArray )
{
foreach ( E element in inputArray )
Console.Write( element + " " );
Console.WriteLine( "\n" );
} // end method PrintArray
} // end class GenericMethod
Comma separated values in SQL Server
13 years ago
Hello Kalit ,
ReplyDeleteI think they are not just templates but they seperate the logic from data type below is a simple video which talks with a demo of what are generics
http://youtu.be/7bKhAJpY9ho?hd=1