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 :) */}

4,706 votes
Sign in
or sign in with
  • facebook
  • google
    Password icon
    I agree to the terms of service
    Signed in as (Sign out)
    You have left! (?) (thinking…)
    Marc SigristMarc Sigrist shared this idea  ·   ·  Flag idea as inappropriate…  ·  Admin →


    Sign in
    or sign in with
    • facebook
    • google
      Password icon
      I agree to the terms of service
      Signed in as (Sign out)
      • jaime weisejaime weise commented  ·   ·  Flag as inappropriate

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

        with(someVariable) { ... }

      • Jeroen LandheerJeroen 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 SigristMarc 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 LewandowskiMarc 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?

      • mgbrownmgbrown 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 motillwill 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 motillwill 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 motillwill 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 GilbertJonathan 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équyFré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#.

      • FelixFelix 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 KalnytskyiGeorgii 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.

      • RSRS 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.

      • NateNate 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.


      • NateNate commented  ·   ·  Flag as inappropriate

        I don't know if it helps any, but it's possible to add a couple things that are still obvious to the consumer of the method and the builder:

        1) Add an attribute that you create that accepts the name of the non-nullable argument/parameter, it's job is to have a method that can be run to ensure that any null value passed in for that parameter is cause for an exception.
        2) The above attribute can be run on the fly, but is publicly available for external calls
        3) An automated test OR Roslyn build-check block of code could be added that can run through all methods with this attribute to ensure that nothing is currently passing in as null obviously/statically in code


        public abstract void RunReport(Item param1, Item param2, string extraInformation);

        then, on second thought, if something like this were to be added in, i would imagine a derivative of that that may allow more flexibility could be to extend the conditionals we can add to methods/classes:

        public abstract void RunReport(Item param1, Item param2, string extraInformation) where param1 not Nullable where param2 not Nullable

        1) this would give us more extensability with conditionals (we could now supply conditionals to a property name, rather than just to a type
        2) this would also allow us to provide more functional conditions that apply to more than just build-time, but still could be applied to build-time (beyond generics)

        What this doesn't do:
        1) Prevent a nullable value store for variables within a closure

        Though, if you want to do that kind of defensive programming, either your methods are too large, or you need to supply structs and primatives, instead, because they already have this desired behavior.

        More often than not, it's preferred not to have extra side effects for your methods anyways, aside from the traditional TrySet methods: bool TryUpdateValueToSomething<TOutVal>(...., out TOutVal value);

        You can always have a blocking or check variable that gets the results of your method call, and then only set if it is not null. I know this doesn't help with the monotonous work being done, but I feel hesitant to say that it's common enough to encourage this need by having a change to the language to support it.

        One more thing to note about supporting non nullable as a type specifier rather than just another conditional is that you now open up a can of worms that were never there to begin with. How does your method handle setting values for ref/out? You now have to do what for those values in that scenario? outVar = default(TOutVar); ?...what if default(TOutVar) is null because we are dealing with a class (instead of the primatives and structs that prevent this behavior automatically?)

        I'm concerned that this buys more trouble than it gains unless we limit just to extending conditionals to support run-time checks and apply to more than just Types and prevent the use of the 'out' and 'ref' specifiers when supplying parameters.

        It just starts to sound more and more like UnitTests, Attributes, custom Build-Check rules via Roslyn, and Assertion statements are more and more the way to go with this.


      ← Previous 1 3 4 5

      Feedback and Knowledge Base