Unintuitive behaviour with struct initialization and default arguments

后端 未结 5 2286
小鲜肉
小鲜肉 2021-02-12 17:52
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:29

    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.

提交回复
热议问题