Fun with .net: No more empty events

23. February 2010

This is the first in a series of blog posts highlighting interesting snippets hacks I have run across. Although these do work, I do not recommend trying them in production code.

Have you ever gotten tired of checking for null before calling events? Take, for example, this block of code:

public delegate void FunHandler();

public class FooBar
{
    public event FunHandler OnSomethingFun;

    private void DoFunStuff()
    {
        if(OnSomethingFun != null)
        {
            OnSomethingFun();
        }
    }
}

 

I don’t remember where I first saw this one, but if you initialize the event to an empty delegate, then you wouldn’t have to check for null. Before you start explaining to me why this is wrong – take a breath, relax, and realize this is all for fun. Remember, don’t try this in production:

public delegate void FunHandler();

public class FooBar
{
    //not recommended
    public event FunHandler OnSomethingFun = ()=>{};

    private void DoFunStuff()
    {
        OnSomethingFun();
    }
}

short link to this post:

.net, Fun with .net ,

Add comment


(Will show your Gravatar icon)

biuquote
  • Comment
  • Preview
Loading