35

I've just added a weak event implementation to a project using Dustin Campbell's WeakEvent class. Although blindly using Code I Found On The Internet™ is generally a bad idea, it's a far better implementation than what I previously hacked together. It seems to work well so far, but in an effort to understand the code I came across the following:

public class WeakEventHandler<T, E> : IWeakEventHandler<E>
    where T : class
    where E : EventArgs
{
    private delegate void OpenEventHandler(T @this, object sender, E e);
    ...

I'm used to declaring delegates types with just the object sender and EventArgs args arguments, so what does the T @this part achieve? Obviously it is declaring something of WeakEventHandler's T generic type but I've never seen @this before (and googling it is understandably hopeless).

Rebecca Scott
  • 2,421
  • 2
  • 25
  • 39
  • 1
    also see here http://stackoverflow.com/questions/724912/does-the-prefix-for-delegates-have-any-special-meaning/724951#724951 – Richard Friend Apr 04 '11 at 09:17

2 Answers2

40

The @this means you can use the keyword this as a variable.

The T is simply the first open generic type of WeakEventHandler<T, E>.

Oded
  • 489,969
  • 99
  • 883
  • 1,009
39

The @ symbol allows you to escape identifiers within your code.

See MSDN -

The rules for identifiers given in this section correspond exactly to those recommended by the Unicode Standard Annex 15, except that underscore is allowed as an initial character (as is traditional in the C programming language), Unicode escape sequences are permitted in identifiers, and the "@" character is allowed as a prefix to enable keywords to be used as identifiers.

http://msdn.microsoft.com/en-us/library/aa664670(VS.71).aspx

They give this lovely example of escaping:

class @class
{
   public static void @static(bool @bool) {
      if (@bool)
         System.Console.WriteLine("true");
      else
         System.Console.WriteLine("false");
   }   
}

Would like to see that one in a code review!

Stuart
  • 66,722
  • 7
  • 114
  • 165