Hacker News new | ask | show | jobs
by christophilus 163 days ago
Yeah. C# has this ages ago— maybe from the beginning- it’s solvable in a variety of ways at the type system level.

The remaining challenge is interfacing with unsafe code. Unsafe code should be required to check all pointers for null before allowing it back into the safe parts of the codebase.

1 comments

C# 2 added "nullable value types". For example bool? is a type which can be true, or false, or null. Does my cat like dry food? True? False? Actually I do not have a cat so that's null. Historically no value types were nullable. In C# 1.0 the bool could only be true or false.

C# 8 added "nullable reference types". For example string? is a type which can be any string, including the empty string "", or it can be null. What's the name of my oldest report? "Steve" ? "Mary" ? No, I do not have anybody reporting to me, it's null. Historically all reference types were nullable, it wasn't optional. In C# 1.0 any string could be null, whereas in C# 8 you could explicitly say that some strings mustn't be null.

However almost all C# software runs on the CLR, and the CLR doesn't believe in these rules, so where your C# is called by other software, possibly not even written in C# you do need to know that all your function boundaries don't actually enforce null checks. This matters most if you write libraries used by third parties in other programming languages, and least for in-house or personal stuff where it clearly goes in the "Don't do that" pile.

Perhaps think of a C# 8.0+ string parameter as a stern "Do not use null strings" sign rather than a firm language commitment like Rust's &str or a C++ &std::string. That new intern will obey it, that nerd who writes machine code for fun will at least know it's their fault if they don't obey it, but the customer on another continent who has apparently never read any of your documentation can't be relied upon to uphold this constraint.

[Edited: fixed numerous typos, there are doubtless more]