20 Feb 2024
Beginner
In C#, both the "is" and "as" keywords are used for type checking and type casting, but they serve different purposes:
- is Keyword:
- The "is" keyword is used for type checking. It returns true if an object is of a specified type, otherwise false.
- It is primarily used in conditional statements or expressions to check if an object is compatible with a certain type before performing operations on it.
- The syntax is
object is Type
.
Example:
object obj = "Hello";
if (obj is string)
{
// obj is a string, perform string operations
}
- as Keyword:
- The "as" keyword is used for explicit type casting (converting one type to another). If the conversion is possible, it returns the converted type; otherwise, it returns null.
- It's primarily used to safely attempt casting an object to a specific type without throwing an exception if the cast fails.
- The syntax is
expression as Type
.
Example:
object obj = "Hello";
string str = obj as string;
if (str != null)
{
// Successfully casted to string, perform string operations
}
else
{
// obj is not a string
}
In summary, "is" is used for type checking while "as" is used for type casting with a safe null check.