The method used to change one data type to another is called type casting. If the prior data type is incompatible with the new data type while type casting one data type to another, we get an exception. We have the IS and AS operators in C# for safe type casting to prevent this exception. Let's learn how to use them both.
The "is" operator is used to determine check whether two objects are of the same type or not. The is keyword returns true if the given object is of the same type.
Example
you might use IS to check if an object is a string before performing certain operations on it.
using System;
using System.Text;
namespace FirstProgram
{
class Program
{
static void Main(string[] args)
{
object obj = "TutorialsTrend";
if (obj is string)
{
Console.WriteLine(obj.ToString().ToUpper());
}
}
}
}
The "as" operator is used to perform safe type conversions. It is used to convert the object of one type to other. It attempts to cast an object to a specified type, and if the cast is successful, returns the object of the specified type. If the cast fails, it returns null.
Example
you might use AS to convert an object to a string:
using System;
using System.Text;
namespace FirstProgram
{
class Program
{
static void Main(string[] args)
{
object obj = "TutorialsTrend";
string str = obj as string;
if (str != null)
{
Console.WriteLine(obj.ToString().ToUpper());
}
}
}
}
In this example, AS attempts to cast the object "obj" to a string. If the cast is successful, the resulting string is assigned to the variable "str". If the cast fails (e.g. if "obj" is not a string), "str" is set to null.
is
when you only need to check the type of an
object and perform some logic based on that.as
when you need to attempt to cast an object
and handle the failure case without
exceptions.S.No. | IS | AS |
---|---|---|
1 | The IS keyword is used to check whether two objects are of the same type or not. | The AS keyword is used to convert the object of one type to other. |
2 | The IS keyword returns true if the given object is of the same type | The AS keyword returns the object of converted type |
3 | The IS keyword returns false if the given object is not of the same type | The AS keyword return null if the conversion failed |
4 | Does not throw an exception | Does not throw an exception, returns null instead |