Underutilised in C#

I find that there are many underutilised features of C#. The following is short list of some of the features I would like to see being used more often.

The ?? operator

When using lazy loading or singleton constructs we often write code similar to this:

    public Address Address
    {
      get

      {
        if (address == null)

        {
          address = loadAddress();
        }
        return address;
      }
    }

This MSDN page explains that the ?? operator returns the left-hand operand if it is not null, or else it returns the right operand. Using ?? we could get the same functionality, with fewer lines of code:

    public Address Address
    {
      get
      {
        address = address ?? loadAddress();
        return address;
      }
    }

Is Null or Empty

Are you getting tired of writing code like this?

if (name == null || name.Equals(string.Empty))
{
// Do something
}

You really should not be using that, replace it with this:

if (String.IsNullOrEmpty(name))
{
// Do something
}

Using this will often allow us to use the ternary operator e.g.

    public string Name
    {
      get
      {
        return (String.IsNullOrEmpty(name) ? UNSPECIFIED : name);
      }
    }

List(T).AsReadOnly

To prevent modifications to a list, return the list wrapped in a read only wrapper. This aids in encapsulation and helps to prevent unwanted changes to collections. This MSDN page provides a good example.

Advertisements