Architect's Log

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

値型とObjectのデフォルト値

C#ではdefaultキーワードはデフォルト値を返します。そこで値型とObjectのデフォルト値を調べてみました。

ソースコード

using System;

namespace ConsoleApplication {
    enum Hoge {
        foo = 0,
        bar = 1
    }

    class Program {
        static void Main(string[] args) {
            Console.WriteLine("bool:{0}", default(bool));
            Console.WriteLine("byte:{0}", default(byte));
            Console.WriteLine("sbyte:{0}", default(sbyte));
            Console.WriteLine("char == '\0':{0}", default(char) == '\0');
            Console.WriteLine("decimal:{0}", default(decimal));
            Console.WriteLine("double:{0}", default(double));
            Console.WriteLine("Single:{0}", default(Single));
            Console.WriteLine("float:{0}", default(float));
            Console.WriteLine("int:{0}", default(int));
            Console.WriteLine("uint:{0}", default(uint));
            Console.WriteLine("long:{0}", default(long));
            Console.WriteLine("ulong:{0}", default(ulong));
            Console.WriteLine("short:{0}", default(short));
            Console.WriteLine("ushort:{0}", default(ushort));
            Console.WriteLine("float:{0}", default(float));
            Console.WriteLine("double:{0}", default(double));
            Console.WriteLine("DateTime:{0}", default(DateTime));
            Console.WriteLine("TimeSpan:{0}", default(TimeSpan));
            Console.WriteLine("enum:{0}", default(Hoge));
            Console.WriteLine("string == null:{0}", default(string) == null);
            Console.WriteLine("object== null:{0}", default(object) == null);
            Console.ReadKey();
        }
    }
}

結果

Stringのデフォルト値が、String.Emptyではなくnullなのは要注意ですね。