Tech Off Post

Single Post Permalink

View Thread: Ideas for C# 5.0
  • Spongman

    exoteric said:

    Unnullability a la

        public struct Unnullable<T> where T : class
        {
            public Unnullable(T x)
            {
                if (x == null)
                    throw new NullReferenceException();
                item = x;
            }
            public T Item
            {
                get
                {
                    return item;
                }
            }
            private readonly T item;
        }
    

    and used as such

        class Foo
        {
            int Bar = 3;
        }
        class Program
        {
            static void Main(string[] args)
            {
                var ufoo = new Unnullable<Foo>(new Foo());
                Console.WriteLine(ufoo.Item);
                Unnullable<Foo> baz; // error
                Unnullable<Foo> bax = null; // error
                Unnullable<Foo> box = (Foo)null; // error
                Console.ReadKey();
            }
        }
    

    with built-in compiler support so we can simply write

    var ufoo = new Foo!(); // type of ufoo is Foo! => Unnullable<Foo> 
    Console.WriteLine(ufoo.bar);

    Even without compiler support it will help catch nullness errors because in this case the compiler just translates ! to Unnullable - a kind of dual of ? which translates to Nullable. And with compiler support you may not even need to explicitly implement as Unnullable<T> although it will probably make the implementation easier.

     

    And of course unnullable classes - where by default the class is unnullable.

    mod up Unnullablfe<T> (although I'd prefer NonNullable<T>). It should be usable in all places types are usable today and the framework should make full use of it. This would obviously require a CLR rev. Languages that support it should mark their assemblies appropriately, those that don't have the implicit casts/expections added for them by the jit.