Direct Casting and is, as Operators Casting in C#

Most of the time in C#, we write programs where we expect compiler to identify if any type mismatches are there in code. However, sometimes we may need to check object type in run-time or may need to convert an object into specific type at run-time. 

There two different ways we can convert the object into a specific type, those are Direct Casting and through “as” operator. 

Direct Casting: We can do direct casting just by converting one type to another type as shown below. 

long lId = 12;
int iId = (int)lId;

Here we just converted long type variable to int variable, and it successfully converts into int based the long variable value. If the long variable value exceeds int type limit, it throws casting exception. 

Direct casting yields the exception that means it throws an exception if casting can’t be done. For example, if we try to convert object type which holds double value to an int type, then our code throws the exception at run-time as shown below. 

 

“as” Operator: Another way, we can convert type to another type through “as” operator as shown below. 

object obj = "string example";
string str = obj as string;

Casting with “as” operator is the same as direct casting, the only difference is if casting fails through “as” operator it won’t return any exception like direct casting; instead it returns null.

class Program
{
        static void Main(string[] args)
        {
            object obj = new Employee(); 
 
            string str = obj as string;
 
            if (str == null)
            {
                Console.WriteLine("Casting failed through as operator");
            }
 
            Console.ReadLine();
        }
} 
 
class Employee
{
}

Here we are converting a class object into string type through “as” operator, and it fails because of type mismatch, but it will not through any exception. Instead of throwing an exception, it simply assigns a null value to a variable if casting fails. 

“is” Operator: “is” operator won’t perform any casting. Instead, it just checks whether the object is a specific type or not. 

class Program
{
        static void Main(string[] args)
        {
            object obj = new Employee(); 

            if (obj is string)
            {
                string str = obj as string;
            }
            else
            {
                Console.WriteLine("Given object is not string type");
            }

            Console.ReadLine();
        }
} 

class Employee
{

}

Here we are checking object type is a string or not by using “is” operator.