I suggest you ...

Add non-nullable reference types in C#

Non-nullability checks have to be manually encoded hundreds of times in any large real-world project, and they are not compile-time-enforced. There are code contracts in .Net 4.0, but their usage is still very verbose, and only partly compile-time-enforced.

What I wish is a pendant to the null-lifting operator ?, for instance, !, so that one could write:
void MyMethod(string! s){ /* s cannot be null :) */}

Or, the way ReSharper does it:
void MyMethod([NotNull] string s){ /* s cannot be null :) */}

6,013 votes
Sign in
or sign in with
  • facebook
  • google
    Password icon
    Signed in as (Sign out)
    You have left! (?) (thinking…)
    Marc Sigrist shared this idea  ·   ·  Flag idea as inappropriate…  ·  Admin →


    Sign in
    or sign in with
    • facebook
    • google
      Password icon
      Signed in as (Sign out)
      • .Net is failing commented  ·   ·  Flag as inappropriate

        Some interesting data from the 2017 Stack Overflow survey.

        C# has fallen in popularity from 45% to 34% in just 5 years.

        And Xamarin is one of the most dreaded technologies in the Stack Overflow survey.


        The only really successful language Microsoft ever developed was classic VB, up to its best version ever - the VB6 programming language. They have never achieved the same success since.

      • jaime weise commented  ·   ·  Flag as inappropriate

        how about creating something like using(...) { ... }* that null checks

        with(someVariable) { ... }

      • Jeroen Landheer commented  ·   ·  Flag as inappropriate

        What I do like would be using this for procedure parameters...

        void MyMethod(someType! value){
        /* s cannot be null, so no need for... */
        if (value == null) throw new ArgumentNullException(nameof(value));


        This means the compiler simply inserts that null check code for us, so we won't have to write it all the time.

      • Marc Sigrist commented  ·   ·  Flag as inappropriate

        I am happy to note that this suggestion has been at the very top ever since I wrote it more than five years ago. To understand its popularity, one can simply enter "billion dollar mistake" into any search engine.

        Non-nullability is difficult to retrofit into a language like C#. There are many approaches, who solve the problem to varying degrees. Furthermore, the discussion is tricky, because people easily mix up the semantics of initialization, nullability, and optionality.

        It is all the more exciting that non-null refs are now in the status of prototyping for the next version after C# 7 (see https://github.com/dotnet/roslyn/blob/master/docs/Language%20Feature%20Status.md).

        Last not least: Several modern programming languages already _have_ null-avoidance features, such as F# (https://docs.microsoft.com/en-us/dotnet/articles/fsharp/language-reference/values/null-values), Swift (https://developer.apple.com/library/content/documentation/Swift/Conceptual/Swift_Programming_Language/Types.html#//apple_ref/swift/grammar/optional-type), or Rust (https://doc.rust-lang.org/std/option/).

      • Marc Lewandowski commented  ·   ·  Flag as inappropriate

        This one is confused right from the title. OP doesn't want non-nullable reference *types*, he wants non-nullable *references*. Confusion throughout the discussion ensues.

        Even that request is problematic: of what use is it? More to the point: are there sufficient cases where a conflict (null reference sent to non-null-reference param) could be detected at compile time to justify the addition of a new language feature?

      • mgbrown commented  ·   ·  Flag as inappropriate

        '"Add non-nullable reference types in C#" that would literally be a struct.'

        Except that it wouldn't follow value semantics like a struct does. The referenced object would have a separate life time to its containing object. It could be shared between multiple referring objects.

      • will motill commented  ·   ·  Flag as inappropriate

        This is basically suggesting that memory be allocated to a reference that potentially is just garbage data this actually would allow others to prevent you from doing a null check on it to find were a problem comes from how would this help anyone ?.

      • will motill commented  ·   ·  Flag as inappropriate

        Btw "Add non-nullable reference types in C#" that would literally be a struct.
        Seriously 4,082 votes to add a struct reference type to c# ?
        Unless 4,082 voters really believe references other then struct's shouldn't need you the programmer to actually give them a value and should be non null if you forget to actually assign a non struct a value ?
        Maybe what is supposed to happen is non structs should use magical energys to divine by supernatural process, Non null and non junk value. Getting these values from beyond the 10th dimension into the non struct Type reference which you forgot to define after declare it, in order to magically initialized it so dat its all ok now ????????<?>?<??...!?>?.

      • will motill commented  ·   ·  Flag as inappropriate

        Was is and even sounds like a bad idea how does this sound.

        Hi im new i have no clue what im doing ya once i wrote a program that made null values i didn't know why but now with non nullable values you can be sure the stuff i give you is not going to crash on the thing that is null. So the junk i send you will run and run then eventually something Else will goof up and crash GG now i feel a lot more pro with non nullable types stuffess :)

      • Jonathan Gilbert commented  ·   ·  Flag as inappropriate

        I think this would have to be implemented as a core runtime feature. In the same way that IL opcodes were added to assist with the new Nullable<T> type in .NET 2.0, what we'd need is a NotNullable<T> struct whose behaviour was special-cased in the CLR.

        This type would have the following properties:

        * It does *not* have a default constructor. Code that attempts to initialize the struct in this way is malformed IL.
        * NotNullable<T> converts to T transparently at the machine code level.
        * Converting T to NotNullable<T> performs a check that the reference is not null. This *could* be done in the C# code implementing NotNullable<T> itself, though we would definitely want the check & conversion to be inlined.
        * To provide support for languages that do not expose any syntactic sugar for it, a public property Value would allow the reference to be extracted as type T.
        * The JIT could omit null reference checks when accessing members of an instance of T via NotNullable<T>, because no valid IL can produce a NotNullable<T> that is a null reference.

        This could then be exposed in languages like C# and VB.NET using a modifier character such as an exclamation point. It would probably make sense for C# to require an explicit cast of T to T!, in keeping with its policy of explicitly showing behaviour. This conversion could, of course, throw a NullReferenceException (in any language).

        Because of the constraint on validity of IL with regards to default initialization of this new struct, compilers targeting the new CLR version would at a minimum need to detect this usage and refuse to compile default(NotNullable<T>) or new NotNullable<T>(). That would be the only change required to be barebones functional with the new type.

      • Frédéric Decréquy commented  ·   ·  Flag as inappropriate

        This is the link to vote to the C sharp contract extension referenced by Felix, in the previous comment for this suggestion : https://visualstudio.uservoice.com/forums/121579-visual-studio-2015/suggestions/3330248-provide-code-constracts-editor-extension-for-vs201

        "Felix commented · May 23, 2016 20:24 · Flag as inappropriate
        Actually, this feature exists in .Net and his name is Code constracts for Visual Studio or C# extension called Spec#. For this validations, it's a best way. I think if you use the CbD's library, your code could be ugly. Then, I suggest add Spec# core into C#.

      • Felix commented  ·   ·  Flag as inappropriate

        Actually, this feature exists in .Net and his name is Code constracts for Visual Studio or C# extension called Spec#. For this validations, it's a best way. I think if you use the CbD's library, your code could be ugly. Then, I suggest add Spec# core into C#.

      • Georgii Kalnytskyi commented  ·   ·  Flag as inappropriate

        Why is the System.Diagnostics.Contracts class not appropriate for this? You might even create a wrapper attribute for using it, I think.

      • RS commented  ·   ·  Flag as inappropriate

        Just my two cents but this seems like a weird request; one, I just hope, it's not seen as a priority.

        The core reason behind this appears to be laziness but, being lazy myself, I believe that there are multiple (and way simpler) approaches to this "problem"; e.g., snippets, T4, the ingenious NonNullable struct, etc. It seems everyone agrees that no suggested solution would be (100%) "safe", so I'm actually amazed of how much energy can go into this.


        P.S. I'm a little surprised by the... "simplicity" of this forum, including the order of the posts --very unfriendly for reading a thread.

      • Nate commented  ·   ·  Flag as inappropriate

        Wish I could edit a past comment...

        But one more thing to note is that System.Nullable<T> has been around since v2, so things like ? and ?. (null-conditional operators) are merely candy to do something the .NET framework has already supported since v2.

        Adding a new wrapper type or functionality to a similar level for something like NonNullable would require more than just a change in the framework, but also to each language that would need to support it (and compiler at that note)...sounds kind of scary for a feature that we've got by without up until now and sounds like it has very little need for.


      Feedback and Knowledge Base