April 2005 - Posts

Non-nullable reference parameters in C#
27 April 05 08:34 PM | alexcampbell | with no comments

Cyrus has been doing some extremely interesting writing on his blog about non-nullable reference types in C#.

C# now supports nullable value types, so non-nullable reference types are really an extension and reversal of this.  However the implementation of the latter turns out to be much more complicated as Cyrus has outlined over 4 ports.

What I wonder is why we can't just have non-nullable reference method parameters, where the compiler ensures that the parameter can't be passed in as null.  This is nice because it accomodates 90% of the scenarios that I can think of but all the checking occurs at compile time.  There are still a few cases where full non-nullable reference types would be useful but parameters would be a great start.

      public void ProcessFiles() {

           

            string s1 = "fish";

            string s2;

            string s3 = null;

 

            ProcessFile("fish"); // compiles

            ProcessFile(s1); // compiles

            ProcessFile(s2); // compiler error

            ProcessFile(s3); // compiler error

            ProcessFile(null); // compiler error

      }

 

      public void ProcessFile(string! fileName) {

            ...

      }

More Posts