Blog Stats
  • Posts - 18
  • Articles - 0
  • Comments - 14
  • Trackbacks - 82

 

Wrapping C# Events with Accessors

It is a given that private members should be wrapped with public accessors for proper encapsulation of class data.  But it is common to see people publicly declaring events, such as with public event EventHandler SomeEventExposingHimself;.  Essentially, this is the same as exposing a private member to the world without accessors, such as with public string SomeStringThatYouShouldNotHaveAccessToDirectly;.  Any subscriber listening for the event is now tied directly to the actual class member.  C# makes it easy to provide accessors for your events, just as it does for class members, with the keywords add and remove. The following is an example of an event properly wrapped with public accessors:

public event EventHandler EventModestlyExposed {

add {

someEventNotWantingToExposeHimself += value;

}

remove {

someEventNotWantingToExposeHimself -= value;

}

}

 

private event EventHandler someEventNotWantingToExposeHimself;

Billy


Feedback

# re: Wrapping C# Events with Accessors

Gravatar Public fields and public event fields are handled differently by the compiler. If you declare the following in a class.

public event EventHandler SomeEvent;

then look at the generated IL, you'll see that it expands it to:

public event EventHandler SomeEvent
{
add {someEvent += value;}
remove {someEvent -= value;}
}

So I would only add the extra code to wrap an event if I was doing something other than what the compiler is doing for me. 8/9/2006 9:44 AM | Haacked

# re: Wrapping C# Events with Accessors

Gravatar Fair enough...so even if it was exposed directly, it would still be trivially simple to wrap it with public accessors down the road and include additional code within the add and/or remove without having to modify the subscriber(s). 8/9/2006 10:44 AM | Billy

# re: Wrapping C# Events with Accessors

Gravatar Correct. 8/9/2006 11:32 AM | Haacked

Post a comment





 

Please add 1 and 1 and type the answer here:

 

 

Copyright © Billy McCafferty