C# Type Operators
Type operators in C# are used to check or cast the type of an object. These operators include:
Key Topics
Example 1: The is Operator
// is Operator Example
object obj = "Hello";
bool result = obj is string;
Console.WriteLine(result); // Outputs True
Output:
True
Code Explanation: The is operator checks if obj is of type string and returns true.
Example 2: The as Operator
// as Operator Example
object obj = "Hello";
string str = obj as string;
if (str != null) {
Console.WriteLine(str); // Outputs Hello
}
Output:
Hello
Code Explanation: The as operator attempts to cast obj to a string. If the cast is successful, str is not null, and the value is printed.
Key Takeaways
- The
isoperator checks if an object is of a specific type. - The
asoperator attempts to cast an object to a specific type, returningnullif it fails.