{"action":"created","issue":{"url":"https://api.github.com/repos/dotnet/roslyn/issues/227","labels_url":"https://api.github.com/repos/dotnet/roslyn/issues/227/labels{/name}","comments_url":"https://api.github.com/repos/dotnet/roslyn/issues/227/comments","events_url":"https://api.github.com/repos/dotnet/roslyn/issues/227/events","html_url":"https://github.com/dotnet/roslyn/issues/227","id":56495921,"number":227,"title":"Proposal for non-nullable references (and safe nullable references)","user":{"login":"Neil65","id":10769418,"avatar_url":"https://avatars.githubusercontent.com/u/10769418?v=3","gravatar_id":"","url":"https://api.github.com/users/Neil65","html_url":"https://github.com/Neil65","followers_url":"https://api.github.com/users/Neil65/followers","following_url":"https://api.github.com/users/Neil65/following{/other_user}","gists_url":"https://api.github.com/users/Neil65/gists{/gist_id}","starred_url":"https://api.github.com/users/Neil65/starred{/owner}{/repo}","subscriptions_url":"https://api.github.com/users/Neil65/subscriptions","organizations_url":"https://api.github.com/users/Neil65/orgs","repos_url":"https://api.github.com/users/Neil65/repos","events_url":"https://api.github.com/users/Neil65/events{/privacy}","received_events_url":"https://api.github.com/users/Neil65/received_events","type":"User","site_admin":false},"labels":[{"url":"https://api.github.com/repos/dotnet/roslyn/labels/Area-Language%20Design","name":"Area-Language Design","color":"5319e7"},{"url":"https://api.github.com/repos/dotnet/roslyn/labels/Feature%20Request","name":"Feature Request","color":"fc2929"},{"url":"https://api.github.com/repos/dotnet/roslyn/labels/Language-C%23","name":"Language-C#","color":"207de5"}],"state":"open","locked":false,"assignee":{"login":"MadsTorgersen","id":6677272,"avatar_url":"https://avatars.githubusercontent.com/u/6677272?v=3","gravatar_id":"","url":"https://api.github.com/users/MadsTorgersen","html_url":"https://github.com/MadsTorgersen","followers_url":"https://api.github.com/users/MadsTorgersen/followers","following_url":"https://api.github.com/users/MadsTorgersen/following{/other_user}","gists_url":"https://api.github.com/users/MadsTorgersen/gists{/gist_id}","starred_url":"https://api.github.com/users/MadsTorgersen/starred{/owner}{/repo}","subscriptions_url":"https://api.github.com/users/MadsTorgersen/subscriptions","organizations_url":"https://api.github.com/users/MadsTorgersen/orgs","repos_url":"https://api.github.com/users/MadsTorgersen/repos","events_url":"https://api.github.com/users/MadsTorgersen/events{/privacy}","received_events_url":"https://api.github.com/users/MadsTorgersen/received_events","type":"User","site_admin":false},"milestone":null,"comments":15,"created_at":"2015-02-04T08:43:39Z","updated_at":"2015-02-27T00:57:57Z","closed_at":null,"body":"# 1. Overview\r\n\r\nThis is my concept for non-nullable references (and safe nullable references) in C#. I have tried to keep my points brief and clear so I hope you will be interested in having a look through my proposal.\r\n\r\nI will begin with an extract from the C# Design Meeting Notes for Jan 21, 2015 (https://github.com/dotnet/roslyn/issues/98):\r\n\r\n*There's a long-standing request for non-nullable reference types, where the type system helps you ensure that a value can't be null, and therefore is safe to access. Importantly such a feature might go along well with proper safe nullable reference types, where you simply cannot access the members until you've checked for null.*\r\n\r\nThis is my proposal for how this could be designed. The types of references in the language would be:\r\n* General References (Dog) - the traditional references we have always had.\r\n* Mandatory References (Dog!)\r\n* Nullable References (Dog?)\r\n\r\nImportant points about this proposal:\r\n\r\n1. There are no language syntax changes other than the addition of the '!' and '?' syntax when declaring (or casting) references.\r\n\r\n2. Null reference exceptions are impossible if the new style references are used throughout the code.\r\n\r\n3. **There are no changes to the actual code compilation, by which I mean we are only adding compiler checks - we are not changing anything about the way that the compiled code is generated. The compiled IL code will be identical whether traditional (general) references or the new types of references are used.**\r\n\r\n4. It follows from this last point that the runtime will not need to know anything about the new types of references. Once the code is compiled, references are references.\r\n\r\n5. All existing code will continue to compile, and the new types of references can interact reasonably easily with existing code.\r\n\r\n6. The '!' and '?' can be added to existing code and, if that existing code is 'null safe' already, the code will probably just compile and work as it is. If there are compiler errors, these will indicate where the code is not 'null safe' (or possibly where the 'null safe-ness' of the code is expressed in a way that is too obscure). The compiler errors will be able to be fixed using the same 'plain old C#' constructs that we have always used to enforce 'null safe-ness'.\r\nConversely, code will continue to behave identically if the '!' and '?' are removed (but the code will not be protected against any future code changes that are not 'null safe').\r\n\r\n7. No doubt there are ideas in here that have been said by others, but I haven't seen this exact concept anywhere. However if I have reproduced someone else's concept it was not intentional! (Edit: I now realise that I have unintentionally stolen the core concept from Kotlin - see http://kotlinlang.org/docs/reference/null-safety.html).\r\n\r\nThe Design Meeting Notes cite a blog post by Eric Lippert (http://blog.coverity.com/2013/11/20/c-non-nullable-reference-types/#.VM_yZmiUe2E) which points out some of the thorny issues that arise when considering non-nullable reference types. I respond to some of his points in this post.\r\n\r\nHere is the Dog class that is used in the examples:\r\n\r\n```csharp\r\npublic class Dog\r\n{\r\n    public string Name { get; private set; }\r\n\r\n    public Dog(string name)\r\n    {\r\n        Name = name;\r\n    }\r\n\r\n    public void Bark()\r\n    {\r\n    }\r\n}\r\n```\r\n\r\n# 2. Background\r\n\r\nI will add a bit of context that will hopefully make the intention of the idea clearer.\r\n\r\nI have thought about this topic on and off over the years and my thinking has been along the lines of this type of construct (with a new 'check' keyword):\r\n\r\n```csharp\r\nDog? nullableDog = new Dog(\"Nullable\");\r\n\r\nnullableDog.Bark(); // Compiler Error - cannot dereference nullable reference (yet).\r\n\r\ncheck (nullableDog)\r\n{\r\n    // This code branch is executed if the reference is non-null. The compiler will allow methods to be called and properties to be accessed.\r\n    nullableDog.Bark(); // OK.\r\n}\r\nelse\r\n{\r\n    nullableDog.Bark(); // Compiler Error - we know the reference is null in this context.\r\n}\r\n```\r\n\r\nThe 'check' keyword does two things:\r\n1. It checks whether the reference is null and then switches the control flow just like an 'if' statement.\r\n2. It signals to the compiler to apply certain rules within the code blocks that follow it (most importantly, rules about whether or not nullable references can be dereferenced).\r\n  \r\nIt then occurred to me that since it is easy to achieve the first objective using the existing C# language, why invent a new syntax and/or keyword just for the sake of the second objective? We can achieve the second objective by teaching the compiler to apply its rules wherever it detects this common construct:\r\n\r\n```csharp\r\nif (nullableDog != null)\r\n```\r\n\r\nFurthermore it occurred to me that we could extend the idea by teaching the compiler to detect other simple ways of doing null checks that already exist in the language, such as the ternary (?:) operator.\r\n\r\nThis line of thinking is developed in the explanation below.\r\n\r\n# 3. Mandatory References\r\n\r\nAs the name suggests, mandatory references can never be null:\r\n\r\n```csharp\r\nDog! mandatoryDog = null; // Compiler Error.\r\n```\r\n\r\nHowever the good thing about mandatory references is that the compiler lets us dereference them (i.e. use their methods and properties) any time we want, because it knows at compile time that a null reference exception is impossible:\r\n\r\n```csharp\r\nDog! mandatoryDog = new Dog(\"Mandatory\");\r\nmandatoryDog.Bark(); // OK - can call method on mandatory reference.\r\nstring name = mandatoryDog.Name; // OK - can access property on mandatory reference.\r\n```\r\n\r\n(See my additional post for more details.)\r\n\r\n# 4. Nullable References\r\n\r\nAs the name suggests, nullable references can be null:\r\n\r\n```csharp\r\nDog? nullableDog = null; // OK.\r\n```\r\n\r\nHowever the compiler will not allow us (except in circumstances described later) to dereference nullable references, as it can't guarantee that the reference won't be null at runtime:\r\n\r\n```csharp\r\nDog? nullableDog = new Dog(\"Nullable\");\r\nnullableDog.Bark(); // Compiler Error - cannot call method on nullable reference.\r\nstring name = nullableDog.Name; // Compiler Error - cannot access property on nullable reference\r\n```\r\n\r\nThis may make nullable references sound pretty useless, but there are further details to follow.\r\n\r\n# 5. General References\r\n\r\nGeneral references are the references that C# has always had. Nothing is changed about them.\r\n```csharp\r\nDog generalDog1 = null; // OK.\r\nDog generalDog2 = new Dog(\"General\"); // OK.\r\n\r\ngeneralDog.Bark(); // OK at compile time, fingers crossed at runtime.\r\n```\r\n\r\n# 6. Using Nullable References\r\n\r\nSo if you can't call methods or access properties on a nullable reference, what's the use of them?\r\n\r\nWell, if you do the appropriate null reference check (I mean just an ordinary null reference check using traditional C# syntax), the compiler will detect that the reference can be safely used, and the nullable reference will then behave (within the scope of the check) as if it were a mandatory reference.\r\n\r\nIn the example below the compiler detects the null check and this affects the way that the nullable reference can be used within the 'if' block and 'else' block:\r\n\r\n```csharp\r\nDog? nullableDog = new Dog(\"Nullable\");\r\n\r\nnullableDog.Bark(); // Compiler Error - cannot dereference nullable reference (yet).\r\n\r\nif (nullableDog != null)\r\n{\r\n    // The compiler knows that the reference cannot be null within this scope.\r\n    nullableDog.Bark(); // OK - the reference behaves like a mandatory reference.\r\n}\r\nelse\r\n{\r\n    // The compiler knows that the reference is null within this scope.\r\n    nullableDog.Bark(); // Compiler Error - the reference still behaves as a nullable reference.\r\n}\r\n```\r\n\r\nThe compiler will also recognise this sort of null check:\r\n\r\n```csharp\r\nif (nullableDog == null)\r\n{\r\n    return;\r\n}\r\n\r\n// The compiler knows that if the reference was null, this code would never be reached.\r\nnullableDog.Bark(); // OK - reference behaves like a mandatory reference.\r\n```\r\n\r\nAnd this:\r\n\r\n```csharp\r\nif (nullableDog == null)\r\n{\r\n    throw new Exception(\"Where is my dog?\");\r\n}\r\n\r\n// The compiler knows that if the reference was null, this code would never be reached.\r\nnullableDog.Bark(); // OK - reference behaves like a mandatory reference.\r\n```\r\n\r\nThe compiler will also recognise when you do the null check using other language features:\r\n\r\n```csharp\r\nstring name1 = (nullableDog != null ? nullableDog.Name : null); // OK\r\nstring name2 = nullableDog?.Name; // OK\r\n```\r\n\r\nHopefully it is now clear that if the new style references are used throughout the code, null reference exceptions are actually impossible. However once the effort has been made to convert the code to the new style references, it is important to guard against the accidental use of general references, as this compromises null safety. There needs to be an attribute such as this to tell the compiler to prevent the use use of general references:\r\n\r\n```csharp\r\n[assembly: AllowGeneralReferences(false)] // Defaults to true\r\n```\r\n\r\nThis attribute could also be applied at the class level, so you could for example forbid general references for the assembly but then allow them for a class (if the class has not yet been converted to use the new style references):\r\n\r\n```csharp\r\n[AllowGeneralReferences(true)]\r\npublic class MyClass\r\n{\r\n}\r\n```\r\n\r\n(See my additional post for more details.)\r\n\r\n# 7. Can we develop a reasonable list of null check patterns that the compiler can recognise?\r\n\r\nI have not listed every possible way that a developer could do a null check; there are any number of complex and obscure ways of doing it. The compiler can't be expected to handle cases like this: \r\n\r\n```csharp\r\nif (MyMethodForCheckingNonNull(nullableDog))\r\n{\r\n}\r\n```\r\n\r\nHowever the fact that the compiler will not handle every case is a feature, not a bug. We don't *want* the compiler to detect every obscure type of null check construct. We want it to detect a finite list of null checking patterns that reflect clear coding practices and appropriate use of the C# language. If the programmer steps outside this list, it will be very clear to them because the compiler will not let them dereference their nullable references, and the compiler will in effect be telling them to express their intention more simply and clearly in their code.\r\n\r\nSo is it possible to develop a reasonable list of null checking constructs that the compiler can enforce? Characteristics of such a list would be:\r\n1. It must be possible for compiler writers to implement.\r\n2. It must be intuitive, i.e. a reasonable programmer should never have to even think about the list, because any sensible code will 'just work'.\r\n3. It must not seem arbitrary, i.e. there must not be situations where a certain null check construct is detected and another that seems just as reasonable is not detected.\r\n\r\nI think the list of null check patterns in the previous section, combined with some variations that I am going to put in a more advanced post, is an appropriate and intuitive list. But I am interested to hear what others have to say.  \r\n\r\nAm I expecting compiler writers to perform impossible magic here? I hope not - I think that the patterns here are reasonably clear, and the logic is hopefully of the same order of difficulty as the logic in existing compiler warnings and in code checking tools such as ReSharper.\r\n\r\n# 8. Converting Between Mandatory, Nullable and General References\r\n\r\nThe principles presented so far lead on to rules about conversions between the three types of references. You don't have to take in every detail of this section to get the general idea of what I'm saying - just skim over it if you want.\r\n\r\nLet's define some references to use in the examples that follow.\r\n\r\n```csharp\r\nDog! myMandatoryDog = new Dog(\"Mandatory\");\r\nDog? myNullableDog = new Dog(\"Nullable\");\r\nDog myGeneralDog = new Dog(\"General\");\r\n```\r\n\r\nFirstly, any reference can be assigned to another reference if it is the same type of reference:\r\n\r\n```csharp\r\nDog! yourMandatoryDog = myMandatoryDog; // OK.\r\nDog? yourNullableDog = myNullableDog; // OK.\r\nDog yourGeneralDog = myGeneralDog; // OK.\r\n```\r\n\r\nHere are all the other possible conversions. Note that when I talk about 'intent' I am meaning the idea that a traditional (general) reference is **conceptually** either mandatory or nullable at any given point in the code. This intent is explicit and self-documenting in the new style references, but it still exists implicitly in general references (e.g. \"I know this reference can't be null because I wrote a null check\", or \"I know that this reference can't or at least shouldn't be null from my knowledge of the business domain\").\r\n\r\n```csharp\r\nDog! mandatoryDog1 = myNullableDog; // Compiler Error - the nullable reference may be null.\r\nDog! mandatoryDog2 = myGeneralDog; // Compiler Error - the general reference may be null.\r\nDog? nullableDog1 = myMandatoryDog; // OK.\r\nDog? nullableDog2 = myGeneralDog; // Compiler Error - makes an assumption about the intent of the general reference (maybe it is conceptually mandatory, rather than conceptually nullable as assumed here).\r\nDog generalDog1 = myMandatoryDog; // Compiler Error - loses information about the intent of the mandatory reference (the general reference may be conceptually mandatory, or may be conceptually nullable if the intent is that it could later be made null).\r\nDog generalDog2 = myNullableDog; // Compiler Error - loses the safety of the nullable reference.\r\n```\r\n\r\nThere has to be some compromise in the last three cases as our code has to interact with existing code that uses general references. These three cases are allowed if an explicit cast is used to make the compromise visible (and perhaps there should also be a compiler warning). \r\n\r\n```csharp\r\nDog? nullableDog2 = (Dog?)myGeneralDog; // OK (perhaps with compiler warning).\r\nDog generalDog1 = (Dog)myMandatoryDog; // OK (perhaps with compiler warning).\r\nDog generalDog2 = (Dog)myNullableDog; // OK (perhaps with compiler warning) .\r\n```\r\n\r\nSome of the conversions that were not possible by direct assignment can be achieved slightly less directly using existing language features:\r\n\r\n```csharp\r\nDog! mandatoryDog1 = myNullableDog ?? new Dog(\"Mandatory\"); // OK.\r\nDog! mandatoryDog2 = (myNullableDog != null ? myNullableDog : new Dog(\"Mandatory\")); // OK.\r\n\r\nDog! mandatoryDog3 = (Dog!)myGeneralDog ?? new Dog(\"Mandatory\"); // OK, but requires cast to indicate that we are making an assumption about the intent of the general reference..\r\nDog! mandatoryDog4 = (myGeneralDog != null ? (Dog!)myGeneralDog : new Dog(\"Mandatory\")); // OK, but requires a cast for the same reason as above.\r\n```\r\n\r\n# 9. Class Libraries\r\n\r\nAs mentioned previously, the compiled IL code will be the same whether you use the new style references or not. If you compile an assembly, the resulting binary will not know what type of references were used in its source code.\r\n\r\nThis is fine for executables, but in the case of a class library, where the goal is obviously re-use, the compiler will need a way of knowing the types of references used in the public method and public property signatures of the library.\r\n\r\nI don't know much about the internal structure of DLLs, but maybe there could be some metadata embedded in the class library which provides this information.\r\n\r\nOr even better, maybe reflection could be used - an enum property indicating the type of reference could be added to the ParameterInfo class. Note that the reflection would be used by the *compiler* to get the information it needs to do its checks - there would be no reflection imposed at runtime. At runtime everything would be exactly the same as if traditional (general) references were used.\r\n\r\nNow say we have an assembly that has not yet been converted to use the new style references, but which needs to use a library that does use the new style references. There needs to be a way of turning off the mechanism described above so that the library appears as a traditional library with only general references. This could be achieved with an attribute like this:\r\n\r\n```csharp\r\n[assembly: IgnoreNewStyleReferences(\"SomeThirdPartyLibrary\")]\r\n```\r\n\r\nPerhaps this attribute could also be applied at a class level. The class could remain completely unchanged except for the addition of the attribute, but still be able to make use of a library which uses the new style references.\r\n\r\n(See my additional post for more details.)\r\n\r\n# 10. Constructors\r\n\r\nEric Lippert's post (see reference in the introduction to this post) also raises thorny issues about constructors. Eric points out that \"the type system absolutely guarantees that ...[class] fields always contain a valid string reference or null\".\r\n\r\nA simple (but compromised) way of addressing this may be for mandatory references to behave like nullable references within the scope of a constructor. It is the programmer's responsibility to ensure safety within the constructor, as has always been the case. This is a significant compromise but may be worth it if the thorny constructor issues would otherwise kill off the idea of the new style references altogether.\r\n\r\nIt could be argued that there is a similar compromise for readonly fields which can be set multiple times in a constructor.\r\n\r\nA better option would be to prevent *any* access to the mandatory field (and to the 'this' reference, which can be used to access it) until the field is initialised:\r\n\r\n```csharp\r\npublic class Car\r\n{\r\n    public Engine! Engine { get; private set; }\r\n\r\n    public Car(Engine! engine)\r\n    {\r\n        Engine.Start(); // Compiler Error\r\n        CarInitializer.Initialize(this); // Compiler Error - the 'this' reference could be used to access Engine methods and properties\r\n        Engine = engine;\r\n        // Can now use Engine and 'this' at will\r\n    }\r\n}\r\n```\r\n\r\nNote that it is not an issue if this forces adjustment of existing code - the programmer has chosen to introduce the new style references and thus will inevitably be adjusting the code in various ways as described earlier in this post.\r\n\r\nAnd what if the programmer initializes the property in some way that still makes everything safe but is a bit more obscure and thus more difficult for the compiler to recognise? Well, the general philosophy of this entire proposal is that the compiler recognises a finite list of sensible constructs, and if you step outside of these you will get a compiler error and you will have to make your code simpler and clearer.\r\n\r\n# 11. Generics\r\n\r\nUsing mandatory and nullable references in generics seems to be generally ok if we are prepared to have a class constraint on the generic class:\r\n\r\n```csharp\r\nclass GenericClass<T>\r\n    where T : class // Need class constraint to use mandatory and nullable references\r\n{\r\n    public void TestMethod(T? nullableRef)\r\n    {\r\n        T! mandatoryRef = null; // Compiler Error - mandatory reference cannot be null\r\n        string s = nullableRef.ToString(); // Compiler Error - cannot dereference nullable reference\r\n    }\r\n}\r\n```\r\n\r\nHowever there is more to think about generics - see comments below.\r\n\r\n# 12. Var\r\n\r\nThis is the way that I think var would work:\r\n\r\n```csharp\r\nvar dog1 = new Dog(\"Sam\"); // var is Dog! (the compiler will keep things as 'tight' as possible unless we tell it otherwise).\r\nvar! dog2 = new Dog(\"Sam\"); // var is Dog!\r\nvar? dog3 = new Dog(\"Sam\"); // var is Dog?\r\nvar dog4 = (Dog)new Dog(\"Sam\"); // var is Dog (see conversion rules - needs cast)\r\n\r\nvar dog1 = MethodReturningMandatoryRef(); // var is Dog!\r\nvar! dog2 = MethodReturningMandatoryRef(); // var is Dog!\r\nvar? dog3 = MethodReturningMandatoryRef(); // var is Dog? (see conversion rules)\r\nvar dog4 = (Dog)MethodReturningMandatoryRef(); // var is Dog (see conversion rules - needs cast)\r\n\r\nvar dog1 = MethodReturningNullableRef(); // var is Dog?\r\nvar! dog2 = MethodReturningNullableRef(); // Compiler Error (see conversion rules)\r\nvar? dog3 = MethodReturningNullableRef(); // var is Dog?\r\nvar dog4 = (Dog)MethodReturningNullableRef(); // var is Dog (see conversion rules - needs cast)\r\n\r\nvar dog1 = MethodReturningGeneralRef(); // var is Dog\r\nvar! dog2 = MethodReturningGeneralRef(); // Compiler Error (see conversion rules)\r\nvar? dog3 = (Dog)MethodReturningGeneralRef(); // var is Dog? (see conversion rules - needs cast)\r\n```\r\n\r\nThe first case in each group would be clearer if we had a suffix to indicate a general reference (say #), rather than having no suffix due to the need for backwards compatibility. This would make it clear that 'var#' would be a general reference whereas 'var' can be mandatory, nullable or general depending on the context.\r\n\r\n# 12. More Cases\r\n\r\nIn the process of thinking through this idea as thoroughly as possible, I have come up with some other cases that are mostly variations on what is presented above, and which would just have cluttered up this post if I had put them all in. I'll put these in a separate post in case anyone is keen enough to read them."},"comment":{"url":"https://api.github.com/repos/dotnet/roslyn/issues/comments/76310769","html_url":"https://github.com/dotnet/roslyn/issues/227#issuecomment-76310769","issue_url":"https://api.github.com/repos/dotnet/roslyn/issues/227","id":76310769,"user":{"login":"gafter","id":3804346,"avatar_url":"https://avatars.githubusercontent.com/u/3804346?v=3","gravatar_id":"","url":"https://api.github.com/users/gafter","html_url":"https://github.com/gafter","followers_url":"https://api.github.com/users/gafter/followers","following_url":"https://api.github.com/users/gafter/following{/other_user}","gists_url":"https://api.github.com/users/gafter/gists{/gist_id}","starred_url":"https://api.github.com/users/gafter/starred{/owner}{/repo}","subscriptions_url":"https://api.github.com/users/gafter/subscriptions","organizations_url":"https://api.github.com/users/gafter/orgs","repos_url":"https://api.github.com/users/gafter/repos","events_url":"https://api.github.com/users/gafter/events{/privacy}","received_events_url":"https://api.github.com/users/gafter/received_events","type":"User","site_admin":false},"created_at":"2015-02-27T00:57:56Z","updated_at":"2015-02-27T00:57:56Z","body":"@dotnetchris There is no way to shoehorn that into the existing IL or C# semantics."}}