Using “value” as an identifier in C#

后端 未结 6 499
感动是毒
感动是毒 2021-01-03 20:02

In writing short helper functions, I often find myself wanting to use the variable identifier \"value\" as an argument. It seems as though Visual Studio compiles this just f

6条回答
  •  星月不相逢
    2021-01-03 20:44

    It is fine to use value as an identifier anywhere outside a set accessor. The C# Language Specification (linking old version) says:

    Since a set accessor implicitly has a parameter named value, it is a compile-time error for a local variable or constant declaration in a set accessor to have that name.

    The Word value is not (and was never) a full keyword in C#, even if it has had this special use in setters ever since C# 1.

    See value (C# Reference) for more.

    Of course, if you have a field (class-level variable) called value and you want to access it from within a set accessor, use this.value (or NameOfYourType.value for static fields).


    For a list of real keywords and contextual "keywords", also see C# Keywords.

提交回复
热议问题