We use as and is to safely convert one type to another without errors. This helps check or change types in a friendly way.
Casting with as and is operators in C Sharp (C#)
Start learning this pattern below
Jump into concepts and practice - no test required
or
Test this pattern10 questions across easy, medium, and hard to know if this pattern is strong
Introduction
Syntax
C Sharp (C#)
Type variable = object as Type; bool check = object is Type;
as tries to convert and returns null if it fails.
is checks if the object is a certain type and returns true or false.
Examples
as to convert obj to a string safely.C Sharp (C#)
object obj = "hello"; string s = obj as string; // s will be "hello"
as returns null because obj is not a string.C Sharp (C#)
object obj = 123; string s = obj as string; // s will be null
is checks the type and returns false here.C Sharp (C#)
object obj = 123; bool isString = obj is string; // false
is returns true because obj is a string.C Sharp (C#)
object obj = "hello"; bool isString = obj is string; // true
Sample Program
This program shows how as returns the string or null, and how is checks the type and prints messages accordingly.
C Sharp (C#)
using System; class Program { static void Main() { object obj1 = "Hello World"; object obj2 = 42; // Using 'as' operator string str1 = obj1 as string; string str2 = obj2 as string; Console.WriteLine(str1 ?? "obj1 is not a string"); Console.WriteLine(str2 ?? "obj2 is not a string"); // Using 'is' operator if (obj1 is string) Console.WriteLine("obj1 is a string"); else Console.WriteLine("obj1 is NOT a string"); if (obj2 is string) Console.WriteLine("obj2 is a string"); else Console.WriteLine("obj2 is NOT a string"); } }
Important Notes
Remember, as only works with reference types or nullable types.
Using is is a quick way to check type before casting.
Using as avoids exceptions but you must check for null after.
Summary
as tries to convert and returns null if it can't.
is checks if an object is a certain type and returns true or false.
Both help write safer code when working with different types.
Practice
1. What does the
as operator do in C#?easy
Solution
Step 1: Understand the
Theasoperator behaviorasoperator attempts to cast an object to a specified type but returns null instead of throwing an exception if the cast fails.Step 2: Compare with other options
It checks if an object is exactly a certain type and returns true or false. describes theisoperator, It converts a value type to a string representation. is unrelated, and It throws an exception if the cast is invalid. is incorrect becauseasdoes not throw exceptions.Final Answer:
It tries to cast an object to a type and returns null if it fails. -> Option AQuick Check:
asreturns null on failure [OK]
Hint: Remember:
as returns null, no exceptions [OK]Common Mistakes:
- Confusing
aswithis - Thinking
asthrows exceptions - Assuming
asworks with value types
2. Which of the following is the correct syntax to check if an object
obj is of type string using the is operator?easy
Solution
Step 1: Recall
The correct syntax to check type isisoperator syntaxif (obj is Type), soif (obj is string)is valid.Step 2: Analyze other options
if (obj as string) { /* code */ } usesasincorrectly in an if condition, if (obj == string) { /* code */ } compares object to type which is invalid, if (obj is (string)) { /* code */ } has unnecessary parentheses.Final Answer:
if (obj is string) { /* code */ } -> Option DQuick Check:
issyntax:obj is Type[OK]
Hint: Use
is like: if (obj is Type) [OK]Common Mistakes:
- Using
asin if condition directly - Comparing object to type with ==
- Adding unnecessary parentheses in
ischeck
3. What is the output of the following code?
object obj = "hello"; string s = obj as string; Console.WriteLine(s != null ? s.ToUpper() : "null");
medium
Solution
Step 1: Analyze the
The objectascastobjholds a string "hello". Usingas stringcasts it successfully, sosis "hello".Step 2: Evaluate the conditional output
Sincesis not null,s.ToUpper()is called, producing "HELLO".Final Answer:
HELLO -> Option AQuick Check:
ascast success means uppercase output [OK]
Hint: If
as cast succeeds, use the object; else null [OK]Common Mistakes:
- Assuming
asthrows exception on failure - Forgetting to check for null after
as - Confusing output case sensitivity
4. Identify the error in this code snippet:
object obj = 123; string s = obj as string; Console.WriteLine(s.Length);
medium
Solution
Step 1: Understand
Sinceascast with incompatible typesobjholds an int (123), casting itas stringreturns null.Step 2: Analyze the usage
Sincesis null, callings.Lengthcauses a null reference exception.Final Answer:
Theascast will fail andswill be null, causing a null reference exception. -> Option BQuick Check:
asreturns null on failure; check before use [OK]
Hint: Always check for null after
as cast before use [OK]Common Mistakes:
- Assuming
isfixes null issues - Not checking
sfor null before accessing members - Thinking
asworks with value types
5. Given the classes:
What is the safest way to call
class Animal { }
class Dog : Animal { public string Bark() => "Woof!"; }What is the safest way to call
Bark() on an Animal reference a that might be a Dog?hard
Solution
Step 1: Understand safe casting with
UsingasascastsatoDogsafely, returning null ifais not aDog.Step 2: Check for null before calling
CheckingBark()d != nullensuresBark()is called only ifais aDog, avoiding exceptions.Step 3: Compare with other options
if (a is Dog) { Console.WriteLine(a.Bark()); } checks type but doesn't cast, soa.Bark()is invalid becauseAnimalhas noBark(). Console.WriteLine(((Dog)a).Bark()); casts without check, risking exceptions. Console.WriteLine(a.Bark()); is invalid becauseAnimalhas noBark().Final Answer:
Dog d = a as Dog; if (d != null) Console.WriteLine(d.Bark()); -> Option CQuick Check:
Useas+ null check for safe cast [OK]
Hint: Use
as then check null before method call [OK]Common Mistakes:
- Casting without checking type first
- Calling methods on base type without override
- Using
isthen casting again unnecessarily
