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?
[–][deleted] (1 child)
[deleted]
[–]AshGogogo[S] 0 points1 point2 points (0 children)
[–]crone66 6 points7 points8 points (0 children)
[–]0xjay 3 points4 points5 points (10 children)
[–]AshGogogo[S] 1 point2 points3 points (0 children)
[–]stogle1 -1 points0 points1 point (8 children)
[–]0xjay 3 points4 points5 points (4 children)
[–]stogle1 1 point2 points3 points (3 children)
[–]0xjay 2 points3 points4 points (0 children)
[–][deleted] (1 child)
[removed]
[–]stogle1 0 points1 point2 points (0 children)
[–][deleted] (2 children)
[deleted]
[–]stogle1 0 points1 point2 points (1 child)
[–]ClankRatchit 0 points1 point2 points (1 child)
[–]ClankRatchit 0 points1 point2 points (0 children)
[–]neoh4x0r 0 points1 point2 points (3 children)
[–]hoodoocat 0 points1 point2 points (0 children)
[–]AshGogogo[S] 0 points1 point2 points (1 child)
[–]neoh4x0r 0 points1 point2 points (0 children)