Tuesday, March 19, 2013

Code: C# when not to use var

I ran into a bug today that might have been avoided if we weren’t using var.  Both old/new methods return a byte array but the second method is incorrect as the ToUnixTime() in the new method returns an int.  Some might say better unit testing would have caught the issue, and that's true, but it's pretty hard to deny that using var introduced a bug.  As a general rule I try to use specific types instead of var for native types (int, long, string, datetime), the word var only saves me a few characters, and as shown below the return type is important.

Old method:
private static byte[] GenTimeStamp(DateTime currentTime)
    long FileTime = currentTime.ToFileTime();

    // convert to milliseconds since Jan 1, 1601 00:00 UTC
    // and subtract milliseconds between Jan 1, 1601 & Jan 1, 1970
    Int64 HostUnixTime = ((Int64)FileTime / 10000) - WINDOWS_TO_UNIX_MAGIC_NUMBER;
    Int64 NetUnixTime = IPAddress.HostToNetworkOrder(HostUnixTime);
    return BitConverter.GetBytes(NetUnixTime);

New/refactored method (data type is int instead of long):
private static byte[] GenTimeStamp(DateTime currentTime)
    var hostUnixTime = currentTime.ToUnixTime();
    var netUnixTime = IPAddress.HostToNetworkOrder(hostUnixTime);

    return BitConverter.GetBytes(netUnixTime);