What is the use of `default` keyword in C#?

前端 未结 6 652
盖世英雄少女心
盖世英雄少女心 2020-11-30 01:38
  1. What is the use of default keyword in C#?
  2. Is it introduced in C# 3.0 ?
6条回答
  •  借酒劲吻你
    2020-11-30 02:20

    The default keyword is contextual since it has multiple usages. I am guessing that you are referring to its newer C# 2 meaning in which it returns a type's default value. For reference types this is null and for value types this a new instance all zero'd out.

    Here are some examples to demonstrate what I mean:

    using System;
    
    class Example
    {
        static void Main()
        {
            Console.WriteLine(default(Int32)); // Prints "0"
            Console.WriteLine(default(Boolean)); // Prints "False"
            Console.WriteLine(default(String)); // Prints nothing (because it is null)
        }
    }
    

提交回复
热议问题