C# @ modifier for methods parameters

后端 未结 6 1604
心在旅途
心在旅途 2021-02-18 13:56

I was using ReSharper plugin on VS2010 and i was generating an interface method. ReSharper put an @ on the parameter name. WHat is that used for?

int Count(Func&         


        
6条回答
  •  故里飘歌
    2021-02-18 14:30

    In many ways, resharper is wrong to do this. where is a contextual keyword, meaning: it only acts as a keyword in some very specific scenarios (i.e. LINQ). In the position indicated, it actually does nothing. It would not be confused as a keyword there, as when the C# language designers add keywords to C# they need to ensure pre-existing code continues to compile (as far as possible), and that would have been legal in earlier C#.

    The usage of @ also confuses/complicates some tools (razor, in particular, since razor already uses @ to indicate the start of code - meaning that for a variable using @ (i.e. @string) sometimes you need @ and sometimes you need @@ - and I know of at least one false-positive IDE warning this can cause).

    However! If the parameter was if or class etc, then @if / @class allows you to use that as a variable name rather than getting confused as a C# keyword. That also isn't a great idea, note. But by the same token, we wouldn't start doing that to all our code (string @name = ... etc) - so why do it here? It isn't needed, and as demonstrated by this question, it has added confusion.

    Personally, though, I'd find a parameter name that isn't a keyword or contextual-keyword.

提交回复
热议问题