is and as operators
Context: is checks if an object is compatible with a given type; as performs a safe cast (returns null if incompatible).
is Operator
Section titled “is Operator”object obj = "Hello";if (obj is string){ Console.WriteLine("It's a string");}
// Pattern matching (C# 7+)if (obj is string s){ Console.WriteLine($"Length: {s.Length}");}as Operator
Section titled “as Operator”object obj = "Hello";string str = obj as string;if (str != null){ Console.WriteLine(str.Length);}// If obj is not a string, str is null (no exception)Difference from Cast
Section titled “Difference from Cast”(string)objthrowsInvalidCastExceptionon failure.asreturnsnull(only for reference types and nullable value types).isdoes not cast; just checks.
Type Pattern
Section titled “Type Pattern”if (shape is Circle circle){ Console.WriteLine($"Radius: {circle.Radius}");}