Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What does "T @this" mean in a delegate declaration?

Tags:

c#

generics

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).

like image 949
Rebecca Scott Avatar asked Apr 04 '11 09:04

Rebecca Scott


2 Answers

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>.

like image 146
Oded Avatar answered Nov 06 '22 02:11

Oded


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!

like image 37
Stuart Avatar answered Nov 06 '22 03:11

Stuart