Several times I've seen ReSharper generate code that looks like this:
delegate void myHandler(int i);
myHandler myHandlerContainer;
...
foreach (Delegate @delegate in myHandlerContainer.GetInvocationList())
{...}
Does the '@' in @delegate give that variable any special semantic meaning?
Or is it just a convention I didn't encounter before?
A delegate is a type that represents references to methods with a particular parameter list and return type. When you instantiate a delegate, you can associate its instance with any method with a compatible signature and return type. You can invoke (or call) the method through the delegate instance.
There are two types of delegates, singlecast delegates, and multiplecast delegates. Singlecast delegate point to single method at a time. In this the delegate is assigned to a single method at a time. They are derived from System.
Delegates are mainly used in implementing the call-back methods and events. Delegates can be chained together as two or more methods can be called on a single event. It doesn't care about the class of the object that it references. Delegates can also be used in “anonymous methods” invocation.
Some more details from MSDN:
The prefix "
@
" enables the use of keywords as identifiers, which is useful when interfacing with other programming languages. The character@
is not actually part of the identifier, so the identifier might be seen in other languages as a normal identifier, without the prefix. An identifier with an@
prefix is called a verbatim identifier. Use of the@
prefix for identifiers that are not keywords is permitted, but strongly discouraged as a matter of style.
from C# Language Specification: 2.4.2 Identifiers.
Prefixing with '@
' therefore allows e.g. to derive from a class named "delegate
" which might be defined in a library written in another language than C#.
In any other case I would not recommend to use this syntax and rather make up identifiers different from the C# keywords (e.g. valu
instead of value
) to increase code readability and avoid confusion whether there is any special meaning attached to it. If it is done, properly comment as to why it was done so that others are aware.
There is also another interesting fact about variable naming mentioned there:
Identifiers containing two consecutive underscore characters (
U+005F
) are reserved for use by the implementation. For example, an implementation might provide extended keywords that begin with two underscores.
The @delegate
is to differentiate the variable name from the delegate
keyword.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With