As we familiar that value of any type can be treated as an object then in the code it is difficult to determine that stored value in object of which type. If we want to write a logic for specific value type then is and as both keywords help to determine the specific object type.
The is keyword used to check run-time type of an object is compatible and used to check object is type of specific object or not. The is keyword checks whether the value on its left side is a compatible instance of the type on the right side.
The is keyword used to check run-time type of an object is compatible and used to check object is type of specific object or not. The is keyword checks whether the value on its left side is a compatible instance of the type on the right side.
if (obj is string) // Check whether obj contains value, compatible with right side specific type
{
// Do Something
}
Where the as operator used to cast an object to a specific type and it returns null if not able to cast. Good to use as keyword, benefits it does not throw an exception when type casting fails.
Basically mostly the as keyword is used to cast Null-able types. If the specified value is not an instance of the specified type then null is returned always.
string str = obj as string;
if (str != null) // str will contain null if not string
{
// Do Something
}