Skip to main content

You are not logged in. Your edit will be placed in a queue until it is peer reviewed.

We welcome edits that make the post easier to understand and more valuable for readers. Because community members review edits, please try to make the post substantially better than how you found it, for example, by fixing grammar or adding additional resources and hyperlinks.

7
  • 5
    This pattern makes sense when you cannot reliably say whether a null returned was an "error signalling null" or an actual value of null, because null is a valid value in that case. So for example on Dictionaries, this pattern makes sense, since null is a valid value to store in a dictionary. As a "guard pattern" it's useless, it does exactly the same in exactly the same amount of code as a null check. Commented Nov 9, 2021 at 6:57
  • 3
    In fact the guard pattern now has two connected variables, a bool and an item and you have to do extra work to let the compiler and static analysis know that they belong together and that their values depend on each other. With a simple null-check any compiler or tool can trivially find out whether the local variable is null or not and give you warnings about it. Resharper did that years before any notion of nullable objects being a special thing in the C# language. Commented Nov 9, 2021 at 7:03
  • 1
    And now that C# has pattern matching, you get pretty if-syntax with null-returns too. Commented Nov 9, 2021 at 8:19
  • 2
    Five years ago, this would have been good advice, But C# has moved on hugely and these days I'd not recommend people write C# in this way. This pattern is much better served these days via T? and pattern matching. Commented Nov 9, 2021 at 9:15
  • 2
    And those 9 lines of code because TryGet() forces me into an if clause are supposed to be better than TEntity entity = Get(id) ?? new TEntity(Guid.NewGuid());? Commented Nov 10, 2021 at 11:56