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

前端 未结 6 658
盖世英雄少女心
盖世英雄少女心 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 01:56

    The most common use is with generics; while it works for "regular" types (i.e. default(string) etc), this is quite uncommon in hand-written code.

    I do, however, use this approach when doing code-generation, as it means I don't need to hard-code all the different defaults - I can just figure out the type and use default(TypeName) in the generated code.

    In generics, the classic usage is the TryGetValue pattern:

    public static bool TryGetValue(string key, out T value) {
        if(canFindIt) {
            value = ...;
            return true;
        }
        value = default(T);
        return false;
    }
    

    Here we have to assign a value to exit the method, but the caller shouldn't really care what it is. You can contrast this to the constructor constraint:

    public static T CreateAndInit() where T : ISomeInterface, new() {
        T t = new T();
        t.SomeMethodOnInterface();
        return t;
    }
    

提交回复
热议问题