Bird
Raised Fist0
C Sharp (C#)programming~10 mins

Casting with as and is operators in C Sharp (C#) - Step-by-Step Execution

Choose your learning style10 modes available

Start learning this pattern below

Jump into concepts and practice - no test required

or
Recommended
Test this pattern10 questions across easy, medium, and hard to know if this pattern is strong
Concept Flow - Casting with as and is operators
Start with object
Check type with 'is'
YesSafe to cast
Use 'as' to cast
Cannot cast
Cast failed
Cast succeeded
First, check if an object is a certain type using 'is'. If yes, cast safely. Alternatively, use 'as' to cast and check for null to see if cast succeeded.
Execution Sample
C Sharp (C#)
object obj = "hello";
if (obj is string s) {
  Console.WriteLine(s.Length);
}
string? str = obj as string;
Console.WriteLine(str?.Length);
This code checks if obj is a string using 'is' and then casts with 'as', printing the string length both times.
Execution Table
StepExpressionEvaluationResultAction
1obj = "hello"Assign string to objobj = "hello"Store string in obj
2obj is string sCheck if obj is stringTrueCast obj to s
3Console.WriteLine(s.Length)s = "hello"5Print length 5
4str = obj as stringTry cast obj to string"hello"Assign to str
5Console.WriteLine(str?.Length)str = "hello"5Print length 5
6EndNo more code-Stop execution
💡 Reached end of code after printing string lengths
Variable Tracker
VariableStartAfter Step 1After Step 2After Step 4Final
objnull"hello""hello""hello""hello"
snullnull"hello""hello""hello"
strnullnullnull"hello""hello"
Key Moments - 2 Insights
Why do we check 'obj is string s' before using s?
Because 'is' checks the type and safely casts only if obj is a string, preventing errors. See step 2 and 3 in execution_table.
What happens if 'obj as string' fails?
It returns null instead of throwing an error. We check for null before using the result. See step 4 in execution_table.
Visual Quiz - 3 Questions
Test your understanding
Look at the execution_table, what is the value of 's' after step 2?
A"hello"
Bnull
C5
Dobj
💡 Hint
Check the 'Result' column for step 2 in execution_table
At which step does the 'as' operator cast happen?
AStep 3
BStep 2
CStep 4
DStep 5
💡 Hint
Look for 'as' in the 'Expression' column in execution_table
If obj was not a string, what would 'str' be after step 4?
A0
Bnull
C"hello"
DException thrown
💡 Hint
Recall that 'as' returns null if cast fails, see key_moments explanation
Concept Snapshot
Casting with 'is' checks type and casts safely:
if (obj is Type t) { use t }

Casting with 'as' tries cast and returns null if fails:
Type? t = obj as Type;
Check for null before use.

Use 'is' to avoid exceptions and 'as' for nullable casts.
Full Transcript
This example shows how to use 'is' and 'as' operators in C# for casting. First, an object 'obj' holds a string "hello". Using 'is', we check if obj is a string and assign it to 's' if true. Then we print the length of 's'. Next, we use 'as' to cast obj to string and assign to 'str'. We print the length of 'str' using null-safe access. The execution table traces each step, showing variable values and actions. Key moments explain why 'is' is used to safely cast and how 'as' returns null if casting fails. The visual quiz tests understanding of variable values and casting steps. The snapshot summarizes the syntax and behavior of 'is' and 'as' casting in C#.

Practice

(1/5)
1. What does the as operator do in C#?
easy
A. It tries to cast an object to a type and returns null if it fails.
B. It checks if an object is exactly a certain type and returns true or false.
C. It converts a value type to a string representation.
D. It throws an exception if the cast is invalid.

Solution

  1. Step 1: Understand the as operator behavior

    The as operator attempts to cast an object to a specified type but returns null instead of throwing an exception if the cast fails.
  2. Step 2: Compare with other options

    It checks if an object is exactly a certain type and returns true or false. describes the is operator, It converts a value type to a string representation. is unrelated, and It throws an exception if the cast is invalid. is incorrect because as does not throw exceptions.
  3. Final Answer:

    It tries to cast an object to a type and returns null if it fails. -> Option A
  4. Quick Check:

    as returns null on failure [OK]
Hint: Remember: as returns null, no exceptions [OK]
Common Mistakes:
  • Confusing as with is
  • Thinking as throws exceptions
  • Assuming as works 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
A. if (obj == string) { /* code */ }
B. if (obj as string) { /* code */ }
C. if (obj is (string)) { /* code */ }
D. if (obj is string) { /* code */ }

Solution

  1. Step 1: Recall is operator syntax

    The correct syntax to check type is if (obj is Type), so if (obj is string) is valid.
  2. Step 2: Analyze other options

    if (obj as string) { /* code */ } uses as incorrectly in an if condition, if (obj == string) { /* code */ } compares object to type which is invalid, if (obj is (string)) { /* code */ } has unnecessary parentheses.
  3. Final Answer:

    if (obj is string) { /* code */ } -> Option D
  4. Quick Check:

    is syntax: obj is Type [OK]
Hint: Use is like: if (obj is Type) [OK]
Common Mistakes:
  • Using as in if condition directly
  • Comparing object to type with ==
  • Adding unnecessary parentheses in is check
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
A. HELLO
B. null
C. hello
D. Runtime error

Solution

  1. Step 1: Analyze the as cast

    The object obj holds a string "hello". Using as string casts it successfully, so s is "hello".
  2. Step 2: Evaluate the conditional output

    Since s is not null, s.ToUpper() is called, producing "HELLO".
  3. Final Answer:

    HELLO -> Option A
  4. Quick Check:

    as cast success means uppercase output [OK]
Hint: If as cast succeeds, use the object; else null [OK]
Common Mistakes:
  • Assuming as throws 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
A. The is operator is used incorrectly.
B. The as cast will fail and s will be null, causing a null reference exception.
C. You cannot use as with value types like int.
D. The code will compile but print 3.

Solution

  1. Step 1: Understand as cast with incompatible types

    Since obj holds an int (123), casting it as string returns null.
  2. Step 2: Analyze the usage

    Since s is null, calling s.Length causes a null reference exception.
  3. Final Answer:

    The as cast will fail and s will be null, causing a null reference exception. -> Option B
  4. Quick Check:

    as returns null on failure; check before use [OK]
Hint: Always check for null after as cast before use [OK]
Common Mistakes:
  • Assuming is fixes null issues
  • Not checking s for null before accessing members
  • Thinking as works with value types
5. Given the classes:
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
A. if (a is Dog) { Console.WriteLine(a.Bark()); }
B. Console.WriteLine(((Dog)a).Bark());
C. Dog d = a as Dog; if (d != null) Console.WriteLine(d.Bark());
D. Console.WriteLine(a.Bark());

Solution

  1. Step 1: Understand safe casting with as

    Using as casts a to Dog safely, returning null if a is not a Dog.
  2. Step 2: Check for null before calling Bark()

    Checking d != null ensures Bark() is called only if a is a Dog, avoiding exceptions.
  3. Step 3: Compare with other options

    if (a is Dog) { Console.WriteLine(a.Bark()); } checks type but doesn't cast, so a.Bark() is invalid because Animal has no Bark(). Console.WriteLine(((Dog)a).Bark()); casts without check, risking exceptions. Console.WriteLine(a.Bark()); is invalid because Animal has no Bark().
  4. Final Answer:

    Dog d = a as Dog; if (d != null) Console.WriteLine(d.Bark()); -> Option C
  5. Quick Check:

    Use as + 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 is then casting again unnecessarily