wasAsked.

Explain type casting of null.

PwC · Role not specified · technical

Published

Asked in 2026 · Software Engineering

Community answers

Posted by wasAsked editorial collection

"Type casting of null" covers what happens when null is converted between types in C#. The rules differ for reference types and value types. 1. Casting null to reference types — always allowed object o = null; string s = (string)o; // OK: s is null Customer c = (Customer)o; // OK: c is null A null reference has no runtime type, so an explicit cast to any reference type succeeds and the result is null. 2. The as operator string? s2 = o as string; // null — as never throws as returns null when the object is null or not of the target type. It works only with reference types and nullable value types. 3. Casting null to non-nullable value types — throws object boxed = null; int n = (int)boxed; // NullReferenceException at runtime A plain int cannot represent null, so unboxing null fails. 4. Casting null to nullable value types — allowed int? maybe = (int?)boxed; // OK: null int? fromLiteral = null; // OK 5. Converting a nullable value to non-nullable int? value = null; int x = (int)value; // InvalidOperationException: Nullable object must have a value int y = value ?? 0; // safe int z = value.GetValueOrDefault(); 6. The is operator and pattern matching with null object? obj = null; bool isString = obj is string; // false — is never matches null for a type pattern if (obj is null) { ... } // the recommended null check (is not null for the opposite) 7. The null literal and typed contexts var x = null; // compile error: cannot infer a type from null string? name = null; // OK var y = (string?)null; // OK: explicitly typed null Method overload calls with null can be ambiguous between reference-type overloads; a cast (Print((string)null)) chooses one. 8. Convert methods Convert.ToInt32(null) returns 0 (for object or string null), unlike a cast — a source of subtle bugs. int.Parse(null) throws ArgumentNullException. Summary: casting null to reference or nullable types yields null; casting or unboxing null to non-nullable value types throws; use as, is, ?? and pattern matching for safe handling.

Ravindra Wadile · · 0 likes

Sign in to add your answer

Related interview topics