Monday, April 8, 2019

Difference between AS and IS in C# ?


The Difference between IS and As is that..
IS - Is Operator is used to Check the Compatibility of an Object with a given Type and it returns the result as a Boolean (True Or False).
AS - As Operator is used for Casting of Object to a given Type or a Class.
Ex. Student s = obj as Student;
is equivalent to:
Student s = obj is Student ? (Student)obj : (Student)null;
Both 'is' and 'as' keywords are used for type casting in C#.

IS Operator

Is Operator is used to Check the Compatibility of an Object with a given Type and it returns the result as a Boolean i.e. True Or False.

if(obj is string)
{
     ...
}
In the above code the keyword checks whether the value on its left side is an instance of the type on the right side.

AS Operator

As Operator is used for Casting of Object to a given Type or a Class. The as keyword is used to cast nullable types if the specified value is not an instance of the specified type.

MyClass myObject = obj as MyClass;

No comments: