Using C# 7.1 default literal in nullable optional argument causes unexpected behavior

只谈情不闲聊 提交于 2021-02-07 11:53:30

问题


C# 7.1 introduces a new feature called "Default Literals" that allows new default expressions.

// instead of writing
Foo x = default(Foo);

// we can just write
Foo x = default;

For Nullable<T> types, the default value is null, and with the usual usage this works as expected:

int? x = default(int?); // x is null

int? x = default; // x is null

However, when I try to use the new default literal as an optional argument (parameter) of a function, it's not working as expected:

static void Foo(int? x = default(int?))
{
    // x is null
}

static void Foo(int? x = default)
{
    // x is 0 !!!
}

To me, this behavior is unexpected and looks like a bug in the compiler.

Can anybody confirm the bug, or explain this behavior?


回答1:


After more research online, I found out that it's a known confirmed bug:

  • https://github.com/dotnet/csharplang/issues/970
  • https://github.com/dotnet/roslyn/issues/22578

It's already fixed and will be part of C# 7.2.



来源:https://stackoverflow.com/questions/46997851/using-c-sharp-7-1-default-literal-in-nullable-optional-argument-causes-unexpecte

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!