Introduction
- At run-time May get information on the types used in a generic type .
- We can create generic classes by starting with pre define class.
- We may create our own generic classes.
- Generics started from framework 2.0.
- Generics allow we to define a class with a replacement holder for the type of its fields, methods, parameters, etc.
- Generics replace these replacement holder with some specific type at compile time.
- A generic class can be defined using angle brackets <>
Description
For example, the letter G denotes a type that is only known based on the calling location.The program can act upon the instance of G like it is a real type, but it is not(In in different sites G refer to T which denotes to Type That may be GT or other)
The Base Class library in c# for Generic is System.Collections.Generic;
In the Introduction I introduced the generic types may used in the method,property and parameters of a class .The bellow example is narates all these.
- class GenericTest<G>
- {
- G _value;
-
- public GenericTest(G t)
- {
-
- this._value = t;
- }
-
- public void Writevalue()
- {
- Console.WriteLine(this._value);
- }
- }
- }
-
-
-
- class GenericClassDemo<G>
- {
-
- private G MemberVariable;
-
-
- public GenericClassDemo(G value)
- {
- MemberVariable = value;
- }
-
- public G Method(G Parameter)
- {
- Console.WriteLine("Generic Parameter : " + typeof(G).ToString() + Parameter.ToString());
- Console.WriteLine("Return Generic type: " + typeof(G).ToString() + MemberVariable.ToString());
-
- return MemberVariable;
- }
-
- public G Property { get; set; }
- }
-
-
-
- public class GenericArray<G>
- {
- private G[] array;
-
- public GenericArray(int size)
- {
- array = new G[size + 1];
- }
- public G getItem(int index)
- {
- return array[index];
- }
- public void setItem(int index, G value)
- {
- array[index] = value;
- }
- }
The Generic Used Classes are Calling in main method those are define bellow,
- class Program
- {
- static void Main(string[] args)
- {
-
- GenericTest<int> gt1 = new GenericTest<int>(50);
-
- gt1.Writevalue();
-
-
- GenericTest<string> gt2 = new GenericTest<string>("c # corner");
- gt2.Writevalue();
-
- callingarryandaclass();
- Console.ReadLine();
- }
-
- static void callingarryandaclass()
- {
- GenericArray<double> doubleArray = new GenericArray<double>(5);
-
-
- for (int c = 0; c < 5; c++)
- {
- doubleArray.setItem(c, c * 5);
- }
-
-
- for (int c = 0; c < 5; c++)
- {
- Console.Write(doubleArray.getItem(c) + " ");
- }
-
- Console.WriteLine();
-
- GenericClassDemo<int> GenericDemo = new GenericClassDemo<int>(10);
-
- int val = GenericDemo.Method(100);
-
- Console.WriteLine("value :" + val);
- }
- }
Generics can also applied to Interface,Abstract class,Static method,Event,Delegates and Operator.
Summery
Generic removes the possibilities of boxing and unboxing and Like Reflection At run-time May get information on the types.