I finished reading CLR via C# about a week ago. If you haven’t read this book and enjoy writing C#, you ought to go out right now and get yourself a copy. This book is amazing, I would have to say that my favorite chapters were on delegates and events. This is seriously a great book.

“When the C# compiler sees the delegate keyword used wherever a reference to a delegate object is expected, the compiler automatically defines a new private method in the class… This new method is called an anonymous method because the compiler creates the name of the method for you automatically, and normally, you wouldn’t know it’s name.” - Jeffrey Richter, CLR via C#

So the below anonymous method would actually get compiled out to a full blown method, with a name given to it by the compiler.

return delegate(T x, T y) { return -comparison(x, y); };

Did you know that you can control event registration and un-registration?

public class EventAggregator< T > where T : EventArgs 
  {
    public EventAggregator( ) 
    {
        _lock = new object( );
    }

    public event EventHandler< T > NewEvent 
    {
          add 
          {
              lock ( _lock ) 
              {
                  _newEvent += value;
              }
          }
          remove 
          {
              lock ( _lock ) 
              {
                  _newEvent -= value;
              }
          }
      }

      public void RaiseEvent( T data ) 
      {
          _newEvent.Invoke( this, data );
      }

      private readonly object _lock;
      private EventHandler< T > _newEvent;
  }

I don’t know about you but the above code blew my mind! “add”, “remove”… whoa! (poof… the sound of my mind blowing up!)

I am seriously looking forward the 3rd edition, where I hope Jeffrey Richter talks about the new additions to the C# compiler in the .NET Framework 3.5. My goodness what are you still doing sitting there… go by this book…

CLR via C#, Second Edition (Pro Developer) by Jeffrey Richter Read more about this title…

comments powered by Disqus