Generics allows you to define type-safe datatypes without declaring any datatypes and also you can write methods and class that works in any datatypes. Lets have a look on generics with the below sample code.
Example
In the above example code you can notice that we have declared a class named MyGenericClass as generic type and in Sample class we are explicitly set the datatype for that class while creating object for it. Example
using System;
using System.Collections.Generic;
namespace GenericsApplication
{
public class MyGenericClass<T>
{
private T[] array;
public MyGenericClass(int size)
{
array = new T[size + 1];
}
public T getItem(int index)
{
return array[index];
}
public void setItem(int index, T value)
{
array[index] = value;
}
}
class Sample
{
static void Main(string[] args)
{
//declaring an int array
MyGenericClass<int> intArray = new MyGenericClass<int>(5);
//setting values
for (int c = 0; c < 5; c++)
{
intArray.setItem(c, c*5);
}
//retrieving the values
for (int c = 0; c < 5; c++)
{
Console.Write(intArray.getItem(c) + " ");
}
Console.WriteLine();
//declaring a character array
MyGenericClass<char> charArray = new MyGenericClass<char>(5);
//setting values
for (int c = 0; c < 5; c++)
{
charArray.setItem(c, (char)(c+97));
}
//retrieving the values
for (int c = 0; c< 5; c++)
{
Console.Write(charArray.getItem(c) + " ");
}
Console.WriteLine();
Console.ReadKey();
}
}
}
Output
0 5 10 15 20
a b c d e
No comments:
Post a Comment