locked
Regarding Cast<> method of Stack in C# RRS feed

  • Question

  • Hi,

    Could you please inform the use of Cast<> method in Stacks.

    It would be great if I come to know the situations where we use and how we can implement it

     

    Thanks

    Prasanna

    • Moved by edhickey Wednesday, July 27, 2011 2:59 PM (From:.NET 3.0/3.5 Windows Workflow Foundation)
    Wednesday, July 27, 2011 6:32 AM

Answers

  • You never execute the cast as the s.Cast<> is deferred, you need to get the array and create new stack.

    Try this instead. Comment out to add the non int and it will break.

    			Stack s = new Stack();
    			s.Push(100);
    			s.Push(200);
    			//s.Push("aaaa");
     
    			Stack<int> intStack = new Stack<int>(s.Cast<int>().ToArray());
     
    			Console.WriteLine(s.Pop().GetType());
    			Console.ReadLine();

    More info

    http://msdn.microsoft.com/en-us/library/bb341406.aspx

    • Marked as answer by Cookie Luo Thursday, August 4, 2011 7:16 AM
    Wednesday, August 3, 2011 12:18 PM
  • 1. Cast<> is not really a method on the Stack class. It's an extension method which applies to all classes implementing IEnumerable<T>.

    2. Stack.Cast<> does not change the elements added to the Stack. It returns a new collection of type IEnumerable<T>, where each element of the Stack are cast to T. The elements of the new collection refer to the same objects as in the Stack, but thy are cast to a new type.

    3. One way to use it. The class Banana inherits from Fruit:

                Stack<Banana> bananas = new Stack<Banana>();
                bananas.Push(new Banana());
                bananas.Push(new Banana());
     
                IEnumerable<Fruit> fruits = bananas.Cast<Fruit>();
     
                MethodWhichRequireAnEnumerationOfFruits(fruits);

     Note: You will not get a class cast exception before you iterate on the fruits enumerable. For example by calling fruits.ToList()

    Regards,
    K

    • Marked as answer by Cookie Luo Thursday, August 4, 2011 7:17 AM
    Wednesday, August 3, 2011 12:39 PM

All replies

  • This is a pretty open ended question.  Cast<> takes a type argument (it is generic) and attempts to cast each of the items in the collection to that type.  the Stack<> class is an implementation of a stack structure and support first in first out functionality.  Did you have a more specific question?

    HTH,

    Patrick

    Wednesday, July 27, 2011 6:33 PM
  • In short, you don't have to implement it. It's already there. You call it like this:

    Stack<Object> stack = new Stack<Object>();
    
    stack.Push(new MyClass());
    stack.Push(new MyClass());
    stack.Push(new MyClass());
    stack.Push(new MyClass());
    
    Stack<MyClass> newStack = stack.Cast<MyClass>();
    
    
    
    

    This will throw an exception if any of the items from the stack can not be converted to the type you request. For example, if I add a new MyClass2 to the stack, then try to call Cast<MyClass>, it will throw an exception if it cannot convert from MyClass2 to MyClass.


    Check out My Blog for tech news, development tips, and other information for geeks like me.
    Wednesday, July 27, 2011 6:40 PM
  • Hi Patrick,

    Thank you for your reply.

    Please have a look into the below code

    class CastEg
        {
            static void Main()
            {
                Stack s = new Stack();
                s.Push(100);
                s.Push(200);
                s.Push("aaaa");           
                s.Cast<int>();
                Console.WriteLine(s.Pop().GetType());
                Console.ReadLine();
               
            }
        }

     

    In the above code, eventhough I have used cast(), for the value "aaaa" I am not getting any compile time/runtime errors and the datatype of "aaaa" is showing "String"

    So I want to know the proper use of cast() and also the situations where we use it.

    Thanks in advance.

     

    Thanks

    Prasanna

     

    Wednesday, August 3, 2011 12:10 PM
  • You never execute the cast as the s.Cast<> is deferred, you need to get the array and create new stack.

    Try this instead. Comment out to add the non int and it will break.

    			Stack s = new Stack();
    			s.Push(100);
    			s.Push(200);
    			//s.Push("aaaa");
     
    			Stack<int> intStack = new Stack<int>(s.Cast<int>().ToArray());
     
    			Console.WriteLine(s.Pop().GetType());
    			Console.ReadLine();

    More info

    http://msdn.microsoft.com/en-us/library/bb341406.aspx

    • Marked as answer by Cookie Luo Thursday, August 4, 2011 7:16 AM
    Wednesday, August 3, 2011 12:18 PM
  • 1. Cast<> is not really a method on the Stack class. It's an extension method which applies to all classes implementing IEnumerable<T>.

    2. Stack.Cast<> does not change the elements added to the Stack. It returns a new collection of type IEnumerable<T>, where each element of the Stack are cast to T. The elements of the new collection refer to the same objects as in the Stack, but thy are cast to a new type.

    3. One way to use it. The class Banana inherits from Fruit:

                Stack<Banana> bananas = new Stack<Banana>();
                bananas.Push(new Banana());
                bananas.Push(new Banana());
     
                IEnumerable<Fruit> fruits = bananas.Cast<Fruit>();
     
                MethodWhichRequireAnEnumerationOfFruits(fruits);

     Note: You will not get a class cast exception before you iterate on the fruits enumerable. For example by calling fruits.ToList()

    Regards,
    K

    • Marked as answer by Cookie Luo Thursday, August 4, 2011 7:17 AM
    Wednesday, August 3, 2011 12:39 PM
  • To create a new Stack you can simply do:

    Stack<int> intStack = new Stack<int>(s.Cast<int>());

    There's no need for .ToArray().

    Regards
    K

    • Marked as answer by Cookie Luo Thursday, August 4, 2011 7:16 AM
    • Unmarked as answer by Cookie Luo Thursday, August 4, 2011 7:16 AM
    Wednesday, August 3, 2011 12:55 PM
  • Thank you so much Andreas and a_Quix for clarifying my confusion

     

    Thanks

    Prasanna

    Monday, August 8, 2011 1:53 AM