Unintuitive behaviour with struct initialization and default arguments

后端 未结 5 1707
半阙折子戏
半阙折子戏 2021-02-12 17:46
public struct Test 
{
    public double Val;
    public Test(double val = double.NaN) { Val = val; }
    public bool IsValid { get { return !double.IsNaN(Val); } }
}

Te         


        
5条回答
  •  囚心锁ツ
    2021-02-12 18:41

    For all value types T, new T() and default(T) are equivalent. They do not call any constructor, they merely set all fields to zero. This is also why C# does not let you write a parameterless constructor: public Test() { Val = double.NaN; } would not compile, because there would be no way for that constructor to be used.

    You've found a corner case. Your constructor looks like it would be used for new T(). Since your type is still a value type, it isn't used. Since your constructor can be called, no error is issued.

提交回复
热议问题