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:
.cf { font-family: Consolas, Courier New, Courier, Monospace; font-size: 9pt; color: black; background: white; }.cl { margin: 0px; }.cb1 { color: blue; }.cb2 { color: #2b91af; }.cb3 { color: green; }

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

Let’s you do this:
.cf { font-family: Consolas, Courier New, Courier, Monospace; font-size: 9pt; color: black; background: white; }.cl { margin: 0px; }.cb1 { color: blue; }.cb2 { color: #a31515; }

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

Instead of checking for null before invocation:
.cf { font-family: Consolas, Courier New, Courier, Monospace; font-size: 9pt; color: black; background: white; }.cl { margin: 0px; }.cb1 { color: blue; }.cb2 { color: green; }.cb3 { color: #a31515; }

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

Chaining the ?? operator:
.cf { font-family: Consolas, Courier New, Courier, Monospace; font-size: 9pt; color: black; background: white; }.cl { margin: 0px; }.cb1 { color: blue; }.cb2 { color: #2b91af; }

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:
.cf { font-family: Consolas, Courier New, Courier, Monospace; font-size: 9pt; color: black; background: white; }.cl { margin: 0px; }.cb1 { color: blue; }.cb2 { color: #a31515; }

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