Tuesday, June 12, 2012

Stack VS Stack(of T)


I will prefer yo use Stack(of T)  instead of Stack because it is type safe and second it will not cast object type  in to appropriate type so performance is better .

Stack:

Stack is non generic type collection from name space(system.collection)
by default it can contain  any type  means it accept system.object(every type reference or value type derived from system.object class). stack work on the principle of  LIFO(Last  in First Out) .

Module Module1

    Sub Main()
        Dim stk As New Stack
        stk.Push(1)
        stk.Push("Second")
        stk.Push(3)
        stk.Push("4th")
        Console.WriteLine("first in List")
        Console.WriteLine(stk.Peek)
        stk.Pop()
        Console.WriteLine("after deque first in List")
        Console.WriteLine(stk.Peek)
        Console.ReadLine()
    End Sub
End Module

Out Put:
first in List
4th
after deque first in List
3

Stack(of T):

Stack(of T)  is  generic type collection from name space(system.collection.generic)
 it can contain a specific type means that its type safe so that you can't insert an integer and string in same list.
Dim lst As New stack(of T)
where "T" can be integer ,string or any type.  if you will assign T as "Object" then it will work same as non generic type.Queue(of T)  work on the principle of  LIFO(Last  in First Out) .

Module Module1
    Sub Main()
        Dim stk As New Stack(Of Integer)
        stk.Push(1)
        stk.Push(2)
        stk.Push(3)
        stk.Push(4)
        Console.WriteLine("first in List")
        Console.WriteLine(stk.Peek)
        stk.Pop()
        Console.WriteLine("after deque first in List")
        Console.WriteLine(stk.Peek)
        Console.ReadLine()
    End Sub
End Module

Out Put:
first in List
4
after deque first in List
3

No comments:

Post a Comment