Timeline for What's wrong with returning null?
Current License: CC BY-SA 4.0
8 events
| when toggle format | what | by | license | comment | |
|---|---|---|---|---|---|
| Nov 25, 2021 at 8:58 | comment | added | VisualMelon |
+1, but worth mentioning https://docs.microsoft.com/en-us/dotnet/api/system.diagnostics.codeanalysis.notnullwhenattribute?view=net-6.0 and friends: Try* methods are more general and don't prescribe any meaning to null, while allowing you to exploit null float analysis at the same time (e.g. github.com/dotnet/runtime/blob/…). They are essential in scenarios where the result is generic to provide a usable API (in the absence of an Option type or similar)
|
|
| Nov 10, 2021 at 19:51 | comment | added | Luaan |
@Peter-ReinstateMonica To be fair, the ternary operator also exists and is extremely commonly used for this kind of thing - var entity = TryGet(..., out var e) ? e : new TEntity(...);. If you really expect this exact pattern though, I'd also stick with ??.
|
|
| Nov 10, 2021 at 11:56 | comment | added | Peter - Reinstate Monica |
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());?
|
|
| Nov 9, 2021 at 9:15 | comment | added | David Arno |
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.
|
|
| Nov 9, 2021 at 8:19 | comment | added | Sebastian Redl | And now that C# has pattern matching, you get pretty if-syntax with null-returns too. | |
| Nov 9, 2021 at 7:03 | comment | added | nvoigt | 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. | |
| Nov 9, 2021 at 6:57 | comment | added | nvoigt |
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.
|
|
| Nov 9, 2021 at 2:36 | history | answered | James D | CC BY-SA 4.0 |