Tuesday 27 May 2014

Difference between direct casting, IS and AS operator in C#

Leave a Comment
In this blog I am going to explain difference between direct casting (normal typecasting), IS and AS operator in C#. In C#, we can type cast data from one data type to another data type using below methods:
  1. Using IS operator
  2. Using AS operator
  3. Direct casting or normal typecasting
1. Using IS operator: IS operator returns true if an object can be cast to a specific type otherwise false.  Since the evaluation result is always a Boolean value so IS operator will never throw an exception.
    class Program
    {
        static void Main(string[] args)
        {
            object number = 6.3;

            //Check if number can be cast to int
            if (number is int) 
            {
                Console.WriteLine("Number can be cast to int");
            }
            else
            {
                Console.WriteLine("Number cannot be cast to int");
            }
        }
    }
Above code will print "Number cannot be cast to int" as number = 6.3 is a float value.

2. Using AS operator: AS operator tries to cast an object to a specific type. It returns null on conversion failure instead of raising an exception.
class Program
    {
        static void Main(string[] args)
        {
            object obj = new object();
            obj = 16;
            string str = obj as string; // str == null

            if (str != null)
            {
                Console.WriteLine("Value is " + str);
            }
            else
            {
                Console.WriteLine("Value is null");
            }           
        }
    }
Above code will print "Value is null".

3. Direct casting or normal typecasting: Direct casting or normal typecasting is most common way of casting one object to another data type. However it throws InvalidCastException exception if casting can’t be done.
class Program
    {
        static void Main(string[] args)
        {
            object obj = new object();
            obj = 16;
            string str = (string)obj; // throws InvalidCastException exception

            if (str != null)
            {
                Console.WriteLine("Value is " + str);
            }
            else
            {
                Console.WriteLine("Value is null");
            }
        }          
    }   
Above code will throw InvalidCastException exception at run time.

Comments and suggestions are most welcome. Happy coding!

0 comments :

Post a Comment