Demanding honesty from function inputs
A truly robust system is not just about what you return; it’s also about what you accept. Guarding your functions against potentially misleading or harmful inputs is paramount in creating predictable, error-resistant applications.
Consider this common scenario: You have a function that expects a certain type of input. However, when a null
value sneaks its way in, your function breaks down, leading to the infamous NullReferenceException
. To mitigate this, C# provides a way to demand honesty from function inputs using nullable reference types.
Let’s say you define a function as follows:
public void UpdateUserProfile(UserProfile profile) { // Some operations on profile }
The intention is clear: the function expects UserProfile
. However, what’s stopping a developer from passing in null
?
Nullable reference types to the rescue
As we discussed earlier, with C# 8.0, nullable reference types...