ADVERTISEMENT
Google AdSense Slot (headerLeaderboard)

Set your Publisher ID in src/config/ads.ts to display live ads.

C# Tutorial• 6 min read

Data Types, Value vs Reference & Nullable References

struct vs class in C#, nullable reference types (string?), and the ?? operator

C# distinguishes between Value Types (stored on the stack) and Reference Types (stored on the heap), featuring Nullable Reference Types to prevent NullReferenceExceptions at compile-time.

Value Types, Reference Types & Null Safety

Value Types (int, float, bool, struct): Directly contain their data.

Reference Types (string, class, object): Store memory references pointing to heap-allocated objects.

Nullable References (string? name): Explicitly declares that a reference variable can hold null.

Null-Coalescing (??): Provides fallback default values: string displayName = inputName ?? "Guest";.

Nullable References and Fallback Operators
string? maybeEmail = null;

// Null-coalescing fallback
string emailToUse = maybeEmail ?? "no-reply@codexia.org";
Console.WriteLine($"Contact: {emailToUse}");

// Null-conditional navigation ?.
int? length = maybeEmail?.Length;
Console.WriteLine($"Length: {length ?? 0}");
ADVERTISEMENT
Google AdSense Slot (inContentBanner)

Set your Publisher ID in src/config/ads.ts to display live ads.

Test Yourself With Exercise

+15 XP

Which operator in C# provides a fallback default value if the left-hand operand evaluates to null?