In C#, is there a way to require that access to a property be null-safe. For properties that may return null, it would be nice to have a compile time error if the property was used without null being tested.
Asked
Active
Viewed 322 times
2
-
They're *considering* adding non-nullable references to a future version of C#, at which point nullable references will probably get more compiler warnings. – Damien_The_Unbeliever Feb 05 '16 at 09:22
-
there is no such thing built-in but you can use plugins like ReSharper which will warn you for such cases – Selman Genç Feb 05 '16 at 09:22
-
Not at compile time no. You could probably use a static analysis tool. There's a nice list here: http://stackoverflow.com/questions/38635/what-static-analysis-tools-are-available-for-c – Mark Feb 05 '16 at 09:24
-
It would be nice to hear from a user of those tools. Perhaps the warnings would be so verbose that no one switches the option on. – bbsimonbb Feb 05 '16 at 09:31
-
Thanks @Damien_The_Unbeliever, a quick google on "non-nullable references to a future version of C#" led me to [this](https://msdn.microsoft.com/en-us/library/dd264808(v=vs.110).aspx), which looks to be the current answer to my problem. – bbsimonbb Feb 05 '16 at 09:58
2 Answers
1
No, that is not possible. If a type is nullable, there is no way to make such a check at compile time. The compiler can't know for sure that a value retrieved is not null at compile time.
What about this code? How do you know someVariable
isn't set to null somewhere? Maybe even with reflection?
public string Property
{
get { return someVariable; }
}
What you should do, is make sure the property is never null, or as a consumer, to handle those cases correctly.

Patrick Hofman
- 153,850
- 22
- 249
- 325
-
"Not possible" is a very strong claim. If the editor can enumerate all references to an identifier, it can surely loop through those references to see if they are 1) null safe 2) an explicit test for null or 3) will throw if null. (I'm not the downvoter) – bbsimonbb Feb 05 '16 at 09:27
-
2No, that is not possible since you can't make such an analysis since you don't know the external factors involved, like reflection. – Patrick Hofman Feb 05 '16 at 09:28
-
1The question doesn’t ask if the compiler can check whether a variable is null, it asks whether the compiler can check that the variable is used without a null check. – Feb 05 '16 at 15:54
0
The null reference is held to be "My Billion Dollar Mistake", by its inventor ! In the absence of non-nullable reference types, use code contracts and the visual studio add-in to minimise null reference exceptions.

bbsimonbb
- 27,056
- 15
- 80
- 110