“is” vs “as” keyword in C#

is Operator In C#

  • In C#, ‘is’ keyword is used to check the data type of an object.
  • In C#, ‘is’ keyword checks whether the conversion from one object type to another object type is compatible or not.
  • It returns boolean.
  • It returns true if the conversion is compatible, else returns false

As Keyword In C#

  • In the development of the software or application, typecasting is a common thing.
  • In many cases, developer need to convert a Type into another Type and sometimes he/she may get InvalidCastException because of invalid type casting.
  • So, to overcome such types of exception C# provides “as” operator keyword.
  • In C#, ‘as’ is a keyword used for conversion from one type to another. The type can be a reference or nullable.
  • In C#, ‘as’ keyword checks the compatibility of one object type with another object type.
  • In case of compatible, it will return the value of the new object type otherwise, null will be returned.
  • If the conversion from one data type to another data type fails, then it will return a null value instead of raising an exception. So, the return value can be null also.

The difference between is and as operators are as follows:

  • In C#, the “is” operator is used to check if the run-time type of an object is compatible with the given type or not whereas “as” operator is used to perform conversion between compatible reference types or Nullable types.
  • In C#, the “is” operator is of boolean type whereas “as” operator is not of boolean type.
  • In C#, the “is” operator returns true if the given object is of the same type whereas “as” operator returns the object when they are compatible with the given type.
  • In C#, the “is” operator returns false if the given object is not of the same type whereas “as” operator return null if the conversion is not possible.
  • In C#, the “is” operator is used for only reference, boxing, and unboxing conversions whereas “as” operator is used only for nullable, reference and boxing conversions

Source Code Of “is” VS “as” Operators In C#

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Is_VS_As_Keyword
    class Program
        static void Main(string[] args)
            // AS OPERATOR
            object a = 456;
            string str = a as string;

            // IS OPERATOR
            //object a = 456;
            //bool check = a is string;

            //if(a is string)
            //    Console.WriteLine("Yes Its a String");
            //    Console.WriteLine("No Its Not a String");


Download Notes From This Blog, Link Given Below


No responses yet

Leave a Reply

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