Sunday, October 26, 2008

 

C# Tips and Tricks

There is a very useful post over at StackOverflow on some of the less known parts of C#. Here are a few of my favourites:

Default Event Handler:

public delegate void MyClickHandler(object sender, string myValue);
public event MyClickHandler Click = delegate { }; // add empty delegate!

Let’s you do this:

public void DoSomething()
{
    Click(this, "foo");
}

Instead of checking for null before invocation:

public void DoSomething()
{
    if (Click != null) // Unnecessary
    {
        Click(this, "foo");
    }
}

Chaining the ?? operator:

string result = val1 ?? val2 ?? val3 ?? String.Empty;

And it never ceases to amaze me that many devs don’t use System.IO.Path.Combine(), instead of:

string path = dir + "\\" + fileName;


    

Powered by Blogger