Vb.net Generics

MyClass stack = new MyClass(3);
stack.Push(1);
stack.Push(2);
stack.Push(3);

To use this implementation for another data type, say String , you need to create another class that uses the string type. Obviously, this is not a very efficient way of writing your class definitions because you now have several versions of essentially the same class to maintain.

To Solve this use
private object[] _elements; in MyClass (insted of private int[] _elements;)
now you can add string and int data to stack.push

MyStack stack = new MyStack(3);
stack.Push(1);
stack.Push(2);
stack.Push(“A”);

The problem with above implementation
//---invalid cast---
int num = (int) stack.Pop();

To resolve this inflexibility, you can make use of generics.

public class MyStack < T >
{
private T[] _elements;
private int _pointer;

_elements = new T[size];

When declaring the private member array _element , you use the generic parameter T instead of a
specific type such as int or string :
private T[] _elements;
In short, you replace all specific data types with the generic parameter T .
You can use any variable name you want to represent the generic parameter. T is chosen as the generic parameter for illustration purposes.

To add the integer itmes use
MyStack < int > stack = new MyStack < int > (3);
stack.Push(1);
stack.Push(2);
stack.Push(3);

To add string items use
MyStack < string > stack = new MyStack < string > (3);
stack.Push(“A”);
stack.Push(“B”);
stack.Push(“C”);

Advantages of Generics
It ’ s not difficult to see the advantages of using generics:
Type safety — Generic types enforce type compliance at compile time, not at runtime (as in the case of using Object ). This reduces the chances of data - type conflict during runtime.Performance — The data types to be used in a generic class are determined at compile time, so there ’ s no need to perform type casting during runtime, which is a computationally costly process.
Code reuse — Because you need to write the class only once and then customize it for use with the various data types, there is a substantial amount of code reuse.

The following table provides a look at the classes contained within the System.Collections.Generic namespace.

Comparer < (Of < (T > ) > )
Dictionary < (Of < (TKey, TValue > ) > )
HashSet < (Of < (T > ) > )
LinkedList < (Of < (T > ) > )
Queue < (Of < (T > ) > )
Stack < (Of < (T > ) > )

Comments

Popular posts from this blog

SQL Sentry Plan Explorer