3

Does C# have Nullable annotation's?

For example in Java

public @Nullable <T extends BaseJsonClass> T getModel(String saveKey, Class<T> type) {

Now when the developer tries to call

Object.getModel().someMethod()

The compiler will warn them that they are not checking for null.

I'm aware of the ? mark at the end of var names in C# like someObject? but the problem with this is that it can be tricky/annoying/JSON models when vars are being used in many places.

Oliver Dixon
  • 7,012
  • 5
  • 61
  • 95
  • Try this, seems the same to the same request. [link](http://stackoverflow.com/questions/291340/mark-parameters-as-not-nullable-in-c-net) – Thennarasan Jul 25 '16 at 07:46
  • Possible duplicate of [C#: How to Implement and use a NotNull and CanBeNull attribute](http://stackoverflow.com/questions/792531/c-how-to-implement-and-use-a-notnull-and-canbenull-attribute) – Zein Makki Jul 25 '16 at 07:46
  • I doubt if something like this is available in c# – Neel Jul 25 '16 at 07:46
  • Sounds like [code-contract](https://msdn.microsoft.com/en-us/library/dd264808(v=vs.110).aspx). – Sinatr Jul 25 '16 at 08:10

2 Answers2

10

C# does not have anything like that - such feature is not a part of the language (yet).

However, if you use ReSharper, you can utilize its Value and Nullability Analysis feature, which allows you to add several attributes to your code: [CanBeNull], [NotNull], [ItemCanBeNull], [ItemNotNull]. The nullability analysis performed by the plugin will take these attributes into account, resulting in the compile-time warnings you ask for.

Pang
  • 9,564
  • 146
  • 81
  • 122
pmbanka
  • 1,902
  • 17
  • 24
  • What has the compiler to do with that? – Mario Dekena Jul 25 '16 at 07:50
  • Well, I imagine the compiler theoretically could make a complex analysis and generate warnings when one does not check for null where he should. But you are right, this is more of a language feature than a compiler one. I'll reword this. – pmbanka Jul 25 '16 at 07:53
6

In short, no.

But it is currently a proposal for future development

Proposal: Nullable reference types and nullability checking

David Pilkington
  • 13,528
  • 3
  • 41
  • 73
  • 1
    As of December 2019, this feature has finally arrived. See https://devblogs.microsoft.com/dotnet/embracing-nullable-reference-types/ for details – leonidos79 Dec 20 '19 at 00:16