C# , “is” operators for object casting check

In c#, when casting one object to another if cast fails for type mismatch then it throws “InvalidCastException”. One solution for handling this is using try catch block and catching these kind of exception in the catch block. for example , you have “Person” and “Employee” class and “Employee” class is inherited from “Person” class. then casting the “Employee” class object to “Person” class will work but casting “Person” class object or any other class object which is not derived from “Employee” class to “Employee” class object will fail. below is the example code of it.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
 
namespace ConsoleApplication1
{
    public class Person
    {
        public string firstName;
        public string lastName;
    }
 
    public class Employee : Person
    {
        public int id;
        public decimal salary;
    }
 
    class Program
    {
        static void Main(string[] args)
        {
            Person p = new Person();
            Employee e1 = new Employee();
            Person p1=(Person)e1;  // Works 
            Employee e2 = (Employee)p; // throws "InvalidCastException"
            Console.ReadLine();
        }
    }
}

.csharpcode, .csharpcode pre
{
font-size: small;
color: black;
font-family: consolas, “Courier New”, courier, monospace;
background-color: #ffffff;
/*white-space: pre;*/
}
.csharpcode pre { margin: 0em; }
.csharpcode .rem { color: #008000; }
.csharpcode .kwrd { color: #0000ff; }
.csharpcode .str { color: #006080; }
.csharpcode .op { color: #0000c0; }
.csharpcode .preproc { color: #cc6633; }
.csharpcode .asp { background-color: #ffff00; }
.csharpcode .html { color: #800000; }
.csharpcode .attr { color: #ff0000; }
.csharpcode .alt
{
background-color: #f4f4f4;
width: 100%;
margin: 0em;
}
.csharpcode .lnum { color: #606060; }

So, In the above code casting Employee to Person works but Person to Employee throws “InvalidCastException”, we can use try catch to handle this. another way can be checking the type of object and casting after that . for that c#, provides “is” operator. lets see how we can use it, below is updated code with “is” operator.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
 
namespace ConsoleApplication1
{
    public class Person
    {
        public string firstName;
        public string lastName;
    }
 
    public class Employee : Person
    {
        public int id;
        public decimal salary;
    }
 
    class Program
    {
        static void Main(string[] args)
        {
            Person p = new Person();
            Employee e1 = new Employee();
 
            if (e1 is Person)
            {
                Person p1 = (Person)e1;  // Works 
                Console.WriteLine("Employee casted to Person");
            }
            else
            {
                Console.WriteLine("Unable to Cast Employee to Person");
            }
            if (p is Employee)
            {
                Employee e2 = (Employee)p; // throws "InvalidCastException"
                Console.WriteLine("Person casted to Employee");
            }
            else
            {
                Console.WriteLine("Unable to cast Person to Employee");
            }
 
            Console.ReadLine();
        }
    }
}

.csharpcode, .csharpcode pre
{
font-size: small;
color: black;
font-family: consolas, “Courier New”, courier, monospace;
background-color: #ffffff;
/*white-space: pre;*/
}
.csharpcode pre { margin: 0em; }
.csharpcode .rem { color: #008000; }
.csharpcode .kwrd { color: #0000ff; }
.csharpcode .str { color: #006080; }
.csharpcode .op { color: #0000c0; }
.csharpcode .preproc { color: #cc6633; }
.csharpcode .asp { background-color: #ffff00; }
.csharpcode .html { color: #800000; }
.csharpcode .attr { color: #ff0000; }
.csharpcode .alt
{
background-color: #f4f4f4;
width: 100%;
margin: 0em;
}
.csharpcode .lnum { color: #606060; }

and below is the console output window.

image

here you can see that the first cast works because Employee is Person but the second cast not because Person is not Employee(Person class is parent of Employee class). by this way we can use c# “is” operator and cast objects safely.

Hope you find this post useful, thanks for reading. 🙂

Advertisements

One thought on “C# , “is” operators for object casting check

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s