C# Variable Name “_” (underscore) only

☆樱花仙子☆ 提交于 2019-12-08 14:33:50

问题


I was just hit with a minor issue in C#, it was just a copy-paste mistake but don't know how C# accept it.

This code gets compiled successfully...HOW

namespace DemoNS
{
    class DemoClass
    {
        String _ = new String('a', 1);        
    }
}

Is there any default significance of variable named _?


回答1:


No, there is no default significance, _ is just a variable name like any other.

I like to use it in similar way to Prolog's anonymous variables: when you're creating a lambda that ignores one of its parameters, you can name it _:

EventHandler handler = (_, e) => Console.WriteLine(e);

On the other hand, I wouldn't use it anywhere else, you should use a descriptive name instead.

EDIT: Note that in C# 7.0, _ sometimes has special meaning. For example, you can write _ = new String('a', 1);, even if you didn't declare a variable named _.




回答2:


Nowadays with C# 7.0 the _ does have significance sometimes. It became the discard operator for the new out var feature. It is used when a function returns a value and you want to notify the compiler that you won't be using it - so it can be optimized out. Or when deconstructing (Another C# 7.0 feature) you can use it to ignore part of the tuple that you are not interested in.

Example out var

void Test(out int i) => i = 1;

Test(out _); // _ was never declared, it will still compile in C# 7.0

var r = _;   // error CS0103: The name '_' does not exist in the current context

Example deconstructing a Tuple

var Person = ("John", "Smith");

var (First, _) = Person; // '_' is not a declared

Debug.Print(First); // prints "John"
Debug.Print(_); // error CS0103: The name '_' does not exist in the current context

A problem arises if you do declare your own variable named _ and then use the discard operator it will cause ambiguity. This issue has been reported Here.

EDIT Above problem is not a problem as @maf-soft points out in comments. If _ was declared it is treated like a regular variable like it was pre C# 7.0.




回答3:


_ is a valid character the same as a or i and syntactically variables can start with _ so a single character name of _ is perfectly syntactically correct. Not a really good choice but will compile and work fine.



来源:https://stackoverflow.com/questions/6308078/c-sharp-variable-name-underscore-only

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