C# Common mistakes

in #programming9 years ago

I thought I would do a piece on some common traps and pitfalls in C# and how to avoid them

Construction order of static variables matters

The order static variables are declared in matters. If you have a static variable that references another make sure the one being referenced is declared first.

// Here someInts IS NOT initialised when used
public static MyObject myObject = new MyObject(someInts);
public static int[] someInts = new[] {0, 1, 2};

// Here someInts IS initialised when used
public static int[] someInts = new[] {0, 1, 2};
public static MyObject myObject = new MyObject(someInts);

try/catch with LINQ

LINQ has lazy evaluation. If you need to try/catch for exceptions with LINQ code ensure it covers where the query is actually executed, not defined.

public static IEnumerable<int> GetAges(IEnumerable<Person> people)
{
    try
    {
        // Not executed yet so can't throw
        return people.Select(p => p.Age);
    }
    catch (Exception ex)
    {
        // Will not catch errors
    }
}

// Now the query runs, outside the try/catch
// The try/catch need to wrap this
var ages = GetAges(people).ToArray();

Unsubscribe from events

Always ensure that when you subscribe to an event that you unsubscribe when you have finished with it. If you fail to unsubscribe and the handler has a longer lifetime than the event source you will stop the event source garbage collecting and cause a memory leak.

Upcasting collections to IEnumerable does not make it immutable

It is not possible to upcast a collection to IEnumerable to stop it being changed by the object/function you have given it to.

// Upcast from Array to IEnumerable
IEnumerable<string> names = new[]{"Fred", "Bill"};

// Someone can do this
string[] backToArray = (string[])names;
names[0] = "Tom";

If you do not want internal state exposed return a copy of it to make sure, this is the sort of bug that is a nightmare to chase down.

Dates

The DateTime object has so many ways to trip you up if you are not careful:

  • Always think about the timezone for the date and what timezone any given operation will return, dates can shift on you when moving between zones.
  • If you must convert from string to dates use a format that is explicit such as "2017-08-03" (YMD), do NOT use "03/08/2017" as this can be 3rd Aug or 8th March depending on your region settings.
  • DateTime is immutable, functions like AddDays() return a new instance, remember to grab the results

If you find this helpful let me know and I will cover some more issues like this in a future piece :)

Happy coding

Woz

Coin Marketplace

STEEM 0.04
TRX 0.32
JST 0.075
BTC 64465.86
ETH 1681.46
USDT 1.00
SBD 0.42