Some tips on writing event handling code in C# .NET

How often do you write repetitive code like this? public delegate void MessageEventHandler(object sender, MessageEventArgs e); [Serializable] public sealed class MessageEventArgs : EventArgs { // some class contents } // … event MessageEventHandler OnMessageArrived; private void RaiseOnMessageArrived(string message) { // BTW, what about thread-safety of this call? if (OnMessageArrived != null) { OnMessageArrived(this, new MessageEventArgs(message)); …

Writing .NET code analysis rules as unit tests

Writing assembly usage rules as unit tests turns out to be unexpectedly simple: [Test] public void Immutable_Types_Should_Be_Immutable() { var decorated = GlobalSetup.Types .Where(t => t.Has<ImmutableAttribute>()); foreach (var type in decorated) { var count = type.GetAllFields().Count(f => !f.IsInitOnly && !f.IsStatic); Assert.AreEqual(0, count, “Type {0} should be immutable”, type); } } This test (based on the functionality …

How to ensure that complex methods are covered with tests

Note: The implementation below is based on NCover, NUnit and CC.NET, but the concept itself does not care about specific tools. We all do unit test coverage to monitor code areas that should be tested. Obviously, not all classes are worth testing. For example, these seem to be reasonable exceptions: Plain old С# classes used just for …