Author : Rahul
Last Modified : 31-Jul-2020
Complexity : Beginner

Difference between is and as keyword in C#


The difference between is and as keywords are as follows:

  • The is keyword is used to check whether two objects are of the same type or not whereas as keyword is used to convert the object of one type to other.
  • The is keyword returns true if the given object is of the same type whereas as keyword returns the object of converted type.
  • The is keyword returns false if the given object is not of the same type whereas as keyword return null if the conversion failed.

Example of "is" operator:

using System; 

// taking a class
public class Test1 { } 

// taking a class, derived from Test1
public class Test2 : Test1 { } 

public class Test { 
  

// Main Method
    public static void Main()
    {
        // creating an instance of class Test1
        Test1 obj1 = new Test1(); 

        // creating an instance of class Test2
        Test2 obj2 = new Test2(); 

        // checking whether 'obj1' is of type 'Test1'
        Console.WriteLine(obj1 is Test1); 

        // checking whether 'obj1' is of type Object class
        Console.WriteLine(obj1 is Object); 

        // checking whether 'obj2' is of type 'Test2'
        Console.WriteLine(obj2 is Test2); 

        // checking whether 'obj2' is of type Object class
        Console.WriteLine(obj2 is Object); 

        // checking whether 'obj2' is of type 'Test1' it will return true as Test2 is derived from Test
        Console.WriteLine(o2 is P1);
    }
} 

Output:

True
True
True
True
True

Example of "as" operator

using System; 

// taking a class
class Test1 { } 

// taking a class
class Test2 { } 

class Test { 

    // Main method
    static void Main()
    { 

        // creating and initializing object array
        object[] obj = new object[4];
        obj[0] = new Test1();
        obj[1] = new Test2();
        obj[2] = "Hello";
        obj[3] = null; 

        for (int i = 0; i < obj.Length; i++) { 

            // using as operator
            string str = obj[i] as string; 

            Console.Write("{0}:",i); 

            // checking for the result
            if (str != null) {
                Console.WriteLine("'" + str + "'");
            }
            else {
                Console.WriteLine("Is is not a string");
            }
        }
    }
}

Output:

0:Is is not a string
1:Is is not a string
2:'Hello'
3:Is is not a string