Architect's Log

I'm a Cloud Architect. I'm highly motivated to reduce toils with driving DevOps.

nullを許容しない参照型クラス

.NETにはnullを許容する値型nullableがあります。
逆にnullを許容しない参照型クラスがあったら、予期しないnull例外を避けられると思い作ってみました。

Unnullable.cs

using System;

namespace UnnullableTest {
    public class Unnullable<T> where T : class {

        public T Item {
            get;
            private set;
        }

        public Unnullable(T value) {
            if (value == null) {
                throw new NullReferenceException("nullを保持することはできません。");
            }
            this.Item = value;
        }
    }
}

Program.cs

試した結果です。

using System;

namespace UnnullableTest {
    class Program {
        static void Main(string[] args) {
            try {
                Unnullable<string> string1 = new Unnullable<string>(null);
            } catch (Exception ex) {
                Console.WriteLine(ex.Message);  // nullを値として保持することはできません。
            }

            Unnullable<string> string2 = new Unnullable<string>("abcde");
            Unnullable<string> string3 = new Unnullable<string>(string2.Item.Substring(0, 3));
            Console.WriteLine(string3.Item);  // abc
            Console.ReadKey();
        }
    }
}