wasAsked.

Explain nullable types. How does int? differ from int?

Capgemini · Full Stack Developer · technical

Published

Year not specified · Software Engineering

Community answers

Posted by wasAsked editorial collection

A nullable value type can hold all the values of its underlying type plus null. In C#, int? is shorthand for System.Nullable<int>. The difference between int and int? - int is a value type that always has a value; its default is 0, and it cannot be null. - int? (Nullable<int>) can hold any int value or null; its default is null. int a = 0; // cannot be null int? b = null; // allowed b = 42; Why nullable types are useful - Representing missing or unknown values, especially from databases where a column allows NULL (an optional discount or end date). - Optional parameters or fields where 0 would be a valid value and cannot mean "not set". Working with nullable values - HasValue and Value: if (b.HasValue) Console.WriteLine(b.Value); // Value throws InvalidOperationException if null - GetValueOrDefault(): returns 0 (or a given default) when null. - Null-coalescing operator: int total = b ?? 0; - Null-coalescing assignment: b ??= 10; - Pattern matching: if (b is int value) { ... } or if (b is not null) { ... } - Conversion: int to int? is implicit; int? to int needs an explicit cast, which throws if null: int c = (int)b; Lifted operators Arithmetic and comparison operators work with nullable values: if either operand is null, the arithmetic result is null. int? x = 5, y = null; int? sum = x + y; // null bool greater = x > y; // false (comparisons with null return false) Boxing behaviour When boxed, a null int? becomes a null reference, and a non-null int? boxes as a plain int. Nullable reference types (C# 8+) — a related but different feature - string? and string are the same runtime type; the ? is a compiler annotation enabling warnings about possible null references (when <Nullable>enable</Nullable> is set). - It does not change runtime behaviour, unlike int?, which is a real different type (Nullable<int> struct). EF Core uses nullable types to decide column nullability: int maps to a NOT NULL column, int? to a nullable column.

Ravindra Wadile · · 0 likes

Sign in to add your answer

Related interview topics