What is Generics Classes? Explanation with a sample code.
This article will explain about Generics classes. How you can use Generics classes in asp.net. The main use of Generics classes is with has tables, stack, queue, linked list and other collections.
A basic sample code is provided in this article. Learn shat is Generics Classes? Generics Classes with a sample code.
What is Generics Classes? Sample code for Generic Classes
Generic classes are available in System.Collections.Generic namespace.
Syntax:public class List
Among the methods of that class is this one:public Add(T item)
T is the placeholder for the type that an instance of the generic class
System.Collections.Generic.List
In defining an instance of the generic class, one
specifies the actual type that the instance will store:
List
Then one can use the Add() method of the generic class instance like so:
myListOfStrings.Add("Hello, World");
A generic interface may be implemented by a generic type or a nongeneric type.
Example:public interface IMyGenericInterface
{
void MyMethod
}
A sample code to understand Generic Class.
public class Printer
{
public void Print
{
if(typeof(T) == typeof(string))
{
Console.WriteLine(argument);
}
else
{
Console.WriteLine(argument.ToString());
}
}
static void Main(string[] arguments)
{
Printer printer = new Printer();
printer.Print
Console.WriteLine("Done");
Console.ReadKey();
}
}