skip to content

Operators, Casts and Conversions

Casts, as and is, implicit and explicit conversions, and operator overloading decide what an expression means. Interviewers ask why a cast throws and when as returns null.

on this pageshow

explore

questions

5

In C#, when does an explicit cast like `(TemperatureReading)item` throw, and when does `item as TemperatureReading` return null instead?

level: juniorimportance: must knowfreq 72%

answer

  1. checked against the run-time type
  2. exception versus null on mismatch
  3. a null input is not a mismatch
  4. as needs a reference or nullable target

basics

~20 s

A cast (T)x throws InvalidCastException when the object's run-time type is incompatible with T, while x as T returns null. For a class target, null passes through both; as needs a reference or nullable target and never runs user-defined conversions.

solid answer

~40 s

Both forms check the object's **run-time type** when the static type alone cannot prove the conversion. If `item` holds a `HumidityReading`, `(TemperatureReading)item` throws `InvalidCastException`, while `item as TemperatureReading` returns `null`. A null `item` is not a mismatch: casting a null reference to a class gives `null`, and so does `as`. `as` handles only reference, nullable, boxing and unboxing conversions, so `boxed as Celsius` on a non-nullable struct is error CS0077, and it never calls a user-defined conversion operator. When the compiler can prove a cast can never succeed, such as between two unrelated sealed classes, it rejects it with CS0030 instead of waiting for run time. I cast when a mismatch is a bug that should fail loudly, and use `as` with a null check when a mismatch is an expected case.

code

csharp · 23 lines
csharp
object?[] feed = [new TemperatureReading(21), new HumidityReading(64), null];

foreach (object? item in feed)
{
    TemperatureReading? t = item as TemperatureReading;
    Console.WriteLine(t is null ? "as -> null" : $"as -> {t.Celsius} C");
}

TemperatureReading? fromNull = (TemperatureReading?)feed[2];
Console.WriteLine($"cast of null -> {(fromNull is null ? "null" : "a reading")}");

try
{
    var wrong = (TemperatureReading)feed[1]!;
}
catch (InvalidCastException ex)
{
    Console.WriteLine($"cast of humidity -> {ex.GetType().Name}");
}

abstract class Reading;
sealed class TemperatureReading(double celsius) : Reading { public double Celsius => celsius; }
sealed class HumidityReading(int percent) : Reading { public int Percent => percent; }

go deeper

for a junior

Recall the two outcomes on a mismatch: the cast throws InvalidCastException and as returns null, and both let a null reference through unchanged.

for a middle

Explain why as is limited to reference and nullable targets (CS0077) and why it never runs user-defined conversions, while a cast does.

for a senior

Argue when a loud cast beats a silent null in production code, and show how an unchecked as result turns a clear error into a distant NullReferenceException.

for a principal

Treat the cast-or-as choice as a statement about invariants: a coding standard can require casts where a mismatch is a bug and reserve as for genuinely optional types.

## Two ways to ask for a narrower type A weather-station dashboard often receives readings through a general-purpose channel: a message bus, a cache or a list typed as `object` or as an abstract `Reading` base class. Before it can read a temperature, it has to treat the value as the more specific `TemperatureReading` class. C# offers two expressions for that step: - the **cast expression** `(TemperatureReading)item`, which performs an explicit conversion and throws when the conversion fails at run time; - the **`as` operator** `item as TemperatureReading`, which performs the same reference conversion but produces `null` when it fails. The C# reference describes `E as T` as producing the same result as `E is T ? (T)(E) : (T)null`, except that `E` is evaluated only once. So `as` is a conditional cast, not a different kind of conversion. ## What happens for each input When the static type of `item` is `object` or `Reading`, the compiler cannot know which object will arrive, so it emits a **run-time type check**. The outcome depends on what the variable holds: | `item` holds | `(TemperatureReading)item` | `item as TemperatureReading` | |---|---|---| | a `TemperatureReading` | the same reference | the same reference | | a `HumidityReading` | throws `InvalidCastException` | `null` | | `null` | `null` | `null` | The last row surprises people. A null reference is not a failed conversion: casting `null` to a class type simply yields `null`. The cast only throws when there is an actual object of an incompatible type. That means code that casts and then dereferences can still hit a `NullReferenceException` later if the source was null. Value types behave differently. Casting an `object` that holds `null` to a non-nullable value type such as `int` or a `Celsius` struct is an **unboxing** of null, and it throws `NullReferenceException`. The rules for unboxing to the exact type belong to the lesson on boxing. ## Where `as` is not allowed The `as` operator considers only **reference, nullable, boxing and unboxing conversions**. Two consequences follow: 1. The target must be able to hold `null`. `boxed as Celsius`, where `Celsius` is a struct, is rejected with CS0077: "The as operator must be used with a reference type or nullable type ('Celsius' is a non-nullable value type)". Writing `boxed as Celsius?` compiles and yields a `Nullable<Celsius>` with no value on a mismatch. 2. `as` never runs a **user-defined conversion operator**. If `Celsius` declares `explicit operator Fahrenheit(Celsius c)`, then `celsius as Fahrenheit?` is error CS0039, because no reference, boxing, unboxing, wrapping or null-type conversion exists. Only a cast expression invokes that operator. ## What the compiler rejects before run time A cast is not always deferred to run time. When the compiler can prove that **no object could ever satisfy the conversion**, it reports an error: - `(HumidityReading)temperatureReading`, between two sealed sibling classes, is error CS0030: "Cannot convert type 'TemperatureReading' to 'HumidityReading'". - The same expression with `as` is error CS0039. - From a base-class or `object` variable the same cast compiles, because such a variable might hold either type, and the check moves to run time. ## Choosing between them The choice is about **what a mismatch means** in that piece of code: - **Use a cast** when a mismatch is a programming error. The `InvalidCastException` is thrown at the exact line with both type names in its message, which is far easier to diagnose than a null that travels. - **Use `as` plus a null check** when a mismatch is a normal case, such as a dashboard widget that only renders temperature readings and skips the rest. - **Never dereference an `as` result without checking it.** That converts a clear `InvalidCastException` into a `NullReferenceException` at some later line. - When the code needs both the test and the typed variable, the `is` operator with a declaration pattern (`item is TemperatureReading t`) does both in one step; patterns are covered in the lesson on type and null tests. The interview signal is precise vocabulary: a cast **throws** on an incompatible object, `as` **yields null** on it, both let `null` through for reference types, and `as` is limited to conversions that can produce `null` and never runs user code.

  • Why does `boxed as Celsius` fail to compile when Celsius is a struct, and what can you write instead?
    `as` must be able to return `null` on a mismatch, and a non-nullable struct cannot hold it, so the compiler reports CS0077. Write `boxed as Celsius?` and check `HasValue`, or use a cast inside a try block if a mismatch is a bug. Casting an `object` holding `null` to `Celsius` would throw `NullReferenceException`, since that is an unboxing of null.
  • Why does a cast between two sealed sibling classes fail to compile, while the same cast from their base class compiles?
    With two unrelated sealed classes the compiler can prove no object is ever both, so it reports CS0030 at compile time. A variable typed as the base class might hold either subclass, so the compiler emits a run-time type check instead, and a wrong object throws `InvalidCastException` when the line runs.
  • What failure replaces the InvalidCastException when code uses `as` but never checks the result?
    A `NullReferenceException`, thrown wherever the null result is first dereferenced, which may be lines or methods later. The original type mismatch is lost from the message, so the bug is harder to trace. That is why `as` only makes sense with a null check right after it.

  • Saying that casting a null reference to a class throws InvalidCastException.
  • Claiming as works on any target type, including int or a struct.
  • Believing as will call a type's explicit conversion operator.
  • Dereferencing an as result without checking it for null.
  • Assuming every impossible cast is only caught at run time.
open as a page

In C#, why does adding two bytes into a byte fail to compile, while assigning an int to a float compiles but may round?

level: middleimportance: should knowfreq 52%

basics

~20 s

C# adds two bytes as int, and int to byte is an explicit narrowing conversion, so CS0266 demands a cast. int to float is implicit because it never loses magnitude, but a float cannot hold every integer above 16,777,216.

open as a page

In a C# units-of-measure library, when should a Celsius conversion operator be implicit rather than explicit, and which declarations does the compiler reject?

level: middleimportance: should knowfreq 45%

basics

~20 s

Make a conversion operator implicit only when it can never throw or lose information; otherwise make it explicit so callers must cast. It must be public static, involve the enclosing type, and avoid interface, base, derived or same-type conversions.

open as a page

When overloading operators on a C# struct such as Celsius, which operators must come in pairs, which cannot be overloaded, and how does && still work?

level: seniorimportance: should knowfreq 40%

basics

~20 s

Operators are public static members taking the declaring type; ==/!=, </>, <=/>= and true/false must be paired (CS0216). =, &&, ||, ?:, the cast (T)x and a[i] cannot be overloaded; && and || come from & or | plus operator true and false.

open as a page

In C# 14, what changes when a class declares `public void operator +=(double reading)` instead of relying on its static `operator +` for `stats += reading`?

level: seniorimportance: nice to knowfreq 15%

basics

~20 s

Without it, stats += reading compiles to stats = stats + reading, creating a new object. A C# 14 instance operator += mutates the object in place, so every alias sees the change; property targets still use the static operator.

open as a page