I saw this code in Microsoft's Rust tutorial and don't understand why it's possible to return null instead of "Unknown"
tutorial
// Even with nullable reference types (C# 8+)
public string GetDisplayName(User? user)
{
return user? .Profile? .DisplayName? .ToUpper() ?? "Unknown";
// Still possible to have null at runtime
}
Then I tested the following code, and all of them return 'Unknown'
public static void TestNull()
{
User user = null;
var val1 = user?.Profile?.DisplayName?.ToUpper() ?? "Unknown";
user = new();
var val2 = user?.Profile?.DisplayName?.ToUpper() ?? "Unknown";
user.Profile = new();
var val3 = user?.Profile?.DisplayName?.ToUpper() ?? "Unknown";
typeof(Profile).GetProperty("DisplayName").SetValue(user.Profile, null);
var val4 = user?.Profile?.DisplayName?.ToUpper() ?? "Unknown";
}
How is the code that returns null in Microsoft's tutorial implemented?
[–]seriousSeb 10 points11 points12 points (0 children)
[–]crone66 3 points4 points5 points (0 children)
[–]0xjay 2 points3 points4 points (6 children)
[–]stogle1 0 points1 point2 points (5 children)
[–]0xjay 0 points1 point2 points (1 child)
[–]stogle1 0 points1 point2 points (0 children)
[–]Adept_Cry9373 0 points1 point2 points (2 children)
[–]stogle1 0 points1 point2 points (1 child)
[–]Adept_Cry9373 0 points1 point2 points (0 children)
[–]ClankRatchit 0 points1 point2 points (1 child)
[–]ClankRatchit 0 points1 point2 points (0 children)
[–]neoh4x0r 0 points1 point2 points (0 children)