Cast Operator

Cast Operator in C# with Examples:

In this article, I am going to discuss the Cast Operator in C# with some examples. Please read our previous article before proceeding to this article where we discussed the ToDictionary Method in C# with some examples. Like ToList, ToArray, ToDictionary, the Cast Operator also belongs to the conversion operators category.

Cast Operator in C#:

The Cast Operator in C# is used to casts all the elements of a collection (System.Collections.IEnumerable) to a specified type and then return a new System.Collections.Generic.IEnumerable<T> collection which contains all the elements of the source sequence cast to the specified type. This method uses deferred execution.

The signature of this method is given below.

Cast Operator in C#Parameters:
  1. source: The System.Collections.IEnumerable that contains the elements to be cast to type TResult.
Type parameters:
  1. TResult: The type to cast the elements of source.

Exceptions: It will throw System.ArgumentNullException when the source is null.  It also throws System.InvalidCastException when an element in the source sequence cannot be cast to the specified type TResult.

Example:

In the following example, the source sequence contains 3 elements and all these three elements are of type integer. So, all these elements are cast to integers.

using System.Linq;
using System.Collections.Generic;
using System;
using System.Collections;

namespace ConversionOperators
{
    class Program
    {
        public static void Main()
        {
            ArrayList list = new ArrayList
            {
                10,
                20,
                30
            };

            IEnumerable<int> result = list.Cast<int>();

            foreach (int i in result)
            {
                Console.WriteLine(i);
            }

            Console.ReadKey();
        }
    }
}

Output: 10 20 30

Example2:

In the following example, the line “list.Add(“40”);” will throw an exception. This is because it is a string value and we are trying to convert it into an int. So, it will throw System.InvalidCastException.

using System.Linq;
using System.Collections.Generic;
using System;
using System.Collections;

namespace ConversionOperators
{
    class Program
    {
        public static void Main()
        {
            ArrayList list = new ArrayList
            {
                10,
                20,
                30,
            };

            //The following statement throws System.InvalidCastException
            list.Add("40");

            IEnumerable<int> result = list.Cast<int>();

            foreach (int i in result)
            {
                Console.WriteLine(i);
            }

            Console.ReadKey();
        }
    }
}
Example3:

In the following example, the source sequence is null. So, when we run the application, it will throw System.ArgumentNullException.

using System.Linq;
using System.Collections.Generic;
using System;
using System.Collections;

namespace ConversionOperators
{
    class Program
    {
        public static void Main()
        {
            ArrayList list = null;

            //Throws System.ArgumentNullException
            IEnumerable<int> result = list.Cast<int>();

            foreach (int i in result)
            {
                Console.WriteLine(i);
            }

            Console.ReadKey();
        }
    }
}

In the next article, I am going to discuss the differences between Cast and OfType operators in C# with an example. Here, in this article, I try to explain the need and use of Cast Operator in C# with some examples. I hope you understood the need and use of Cast Operator.

Leave a Reply

Your email address will not be published. Required fields are marked *