Throwing exceptions the right way

Use ReSharper? Notice every time ReSharper sees code like this:

catch (Exception ex)
{
    // some exception handling, or logging here
    throw ex;
}

it complains, and tells you to get rid of the ex for the reason ‘Exception rethrow possibly intended’?

The reason ReSharper is warning you about an ‘exception rethrow’ is that when you rethrow an exception it replaces the stack trace of the original exception with the current location. So if you print the stack trace further up the code you will not be able to see the statement which caused the exception in the first place!

For this reason, you should ALWAYS use this instead:

catch (Exception ex)
{
    // exception handling
    throw;
}

Handling multiple exceptions

Further on exception handling, if your code might throw multiple types of exceptions and you want to handle the exceptions differently then you can build up a hierarchy of catch clauses from the most specific (SqlException e.g.) at the top, to the least specific (Exception) at the bottom like this:

try
{
    // do something that can might throw an exception
}
catch (SqlException sqlEx)
{
    // retry on timeout or deadlock for example?
}
catch (Exception ex)
{
    // handle more generic exception
}
finally
{
    // put any clean up operations here
}

It’s worth noting that, if you are catching the more general exceptions further up the chain your exception handling code for more specific types of exception lower down the list will never be called! But fortunately tools like ReSharper will warn you first :-)

Another thing you might want to consider is to wrap the built-in exception types into a custom Exception type and maybe use an enum to categorise the different exceptions into well defined types that your application understands (e.g. ServerError, FeedError, DatabaseError, etc.).

In the case of WCF services, you can also specify fault contracts for each operation and in your catch clauses on the server side wrap all exceptions into faults so when exceptions happen they don’t fault your channel. For more on WCF error handling and fault conversion, have a look at this article.

Controlling Type conversion in C#

Ever run into a situation where your application needs to use a type for its internal working but occasionally need to convert that type into another just so it can be passed to another application which doesn’t understand some of the base types we have in the .Net space?

Consider the example below, where the Player is a type in my problem domain, but I need to communicate information about the player with a non-.Net client which doesn’t have the Guid type, so I need to have a PlayerDTO type used exclusively for message passing:

public sealed class Player
{
    public Player(string name, long score)
    {
        Name = name;
        Score = score;
        ID = Guid.NewGuid();
    }

    public string Name { get; private set; }
    public Guid ID { get; private set; }
    public long Score { get; private set; }
}

public sealed class PlayerDTO
{
    public PlayerDTO(string name, long score, string id)
    {
        Name = name;
        Score = score;
        ID = id;
    }

    public string Name { get; private set; }
    public string ID { get; private set; } // client is not .Net based so no Guid there
    public long Score { get; private set; }
}

The problem here is that there is no easy way to convert the Player type to PlayerDTO and every time I want to create a new PlayerDTO object I need to manually copy the values from Player into PlayerDTO’s constructor, and my application needs to know that it needs to convert Player.PlayerID into a string.

A cleaner solution here is to overload either the implicit or explicit converter so you can simply cast a Player object into a PlayerDTO object:

// Overload explicit cast converter to allow easy conversion from a Winner to WinnerAmfvo object
public static explicit operator PlayerDTO(Player player)
{
    return new PlayerDTO(player.Name, player.Score, player.PlayerID.ToString());
}

Further more, this allows you to easily convert an array of Player objects into an array of PlayerDTO objects:

// use Array.ConvertAll
PlayerDTO[] playerDTOs = Array.ConvertAll(players, p => (PlayerDTO) p);
// use Linq
playerDTOs = players.Select(p => (PlayerDTO) p).ToArray();

No Interface types allowed

One thing to bear in mind when using the implicit/explicit operators is that you won’t be able to use interface types, and the reason is specified in Section 10.9.3 of the C# spec.

In short, defining an implicit or explicit conversion between reference types gives the user the expectation that there will be a change in reference; after all, the same reference cannot be both types. On the other hand, the user does not have the same expectation for conversions between reference types and interface types.

In these cases, you still have other ways to make type conversion cleaner and centralised, for example:

Create a FromIPlayer method


playerDTOs = iPlayers.Select(p => PlayerDTO.FromPlayer(p)).ToArray();

Put all conversions in a PlayerConvert static object

If you have lots of types which can be converted to many types then it might be a cleaner solution to just put all the conversions into one static object, like the System.Convert class. You then use it like this:


playerDTOs = iPlayers.Select(p => PlayerConvert.ToPlayerDTO(p)).ToArray();

References:

StackOverflow question on why you can't use interface types with implicit/explicit operator

Feb 11th – Scott Guthrie Talks Shop IV

This is an upcoming web seminar with Scott Gu, organised by the good folks at Linked .Net User Group (http://www.lidnug.org).

I attended one of their previous presentations with Joe Albahari on the new features in C# 4.0 (the recorded presentation can be viewed here) and thoroughly enjoyed that! A FREE web seminar with someone as influential in the .Net space as Scott Gu’s gotta be good!

Who those of you who doesn’t know who Scott Gu is, he’s a VP and one of the founding members of the Microsoft’s .Net platform and runs the development teams responsible for Visual Studio developer tools and technologies for building web applications (e.g. ASP.NET MVC).

(Unconfirmed story!) Whilst still an intern, he developed the original ASP.NET platform with another senior developer at Microsoft, just to give you some idea about who the man is :-)

The link to the event is:

https://www.livemeeting.com/cc/microsoft/join?id=G2K4BH&role=attend&pw=PN6.%3CQ%5Drb

and to find out what time it starts in your time zone, go here:

http://www.timeanddate.com/worldclock/fixedtime.html?month=2&day=11&year=2010&hour=10&min=0&sec=0&p1=256

In the meantime, check out Scott Gu’s excellent blog!

Garbage Spewers

I spent a bit of time on Ayende’s blog today, finally catching up with a series of performance-related blog posts he made whilst working on the .Net profiler (the man’s a living legend, the quality AND quantity of his posts is without equal!)

Whilst reading through the various posts, I came across an unfamiliar term – garbage spewers – in patterns for reducing memory usage. To quote from the blog:

Garbage spewers are pieces of code that allocate a lot of memory that will have to be freed soon afterward.

Ayende highlight a common case of garbage spewers where you continuously concatenate a string using +=:

public string Concat(string[] items)
{
   string result = "";
   foreach(var item in items)
      results += item;
   return result;
}

As you know, string is an immutable type in .Net, that is, a type that cannot be updated once it’s been created. Therefore every time results += item is run a new string variable has to be created to hold the concatenated value of results and item, and the reference pointer stored in the results variable is updated to point to the newly created string.

As Ayende pointed out, this loop can consume a lot of memory which will be cleaned up eventually at the expense of a performance hit as this puts more pressure on the GC.

Other common cases involve loading and converting Data Transfer Objects from the database into various different forms and consuming a lot of memory unnecessarily along the way.

Threading – Using ReaderWriterLockSlim

When dealing with concurrency/threading issues in .Net, the normal approach is to use lock() to lock a dedicated sync object like this:

private static readonly object padlock = new object();
…
lock(padlock)
{
     // enter critical section here
}

This is an efficient, simple and well proven way to get thread-safety in .Net and is probably all you’ll ever need in your project. However, as this approach ensures only one thread can enter the critical section at any one time it’s not ideal for managing access to a shared resource because all read and write operations must be made sequentially and this results in a performance hit on your application. Ideally all threads should be able to read the shared resource simultaneously but only one thread can update it and no other threads can read from the resource whilst the update is happening.

.Net’s answer to this used to be the ReaderWriterLock, which since .Net 3.5 has been superseded by the better, more lightweight and performing ReaderWriterLockSlim which Microsoft is recommending for all new development.

The ReaderWriterLockSlim has three modes: Read, Ungradeable and Write:

  • many threads can enter Read lock simultaneously
  • only one thread can enter Ungradeable lock but other threads can still enter Read lock
  • only one thread can enter Write lock and no other thread can enter any lock

In practice though, almost all threading problems can be solved using read and write locks alone. To enter read/write lock, you need something like this:

private static readonly ReaderWriteLockSlim rwlock = new ReaderWriterLockSlim();
…
rwlock.EnterReadLock()
try
{
     // do something here
}
finally
{
     // don't forget to release the lock afterwards!
     rwlock.ExitReadLock();
}

As you can see, this can seriously clutter your code if you require read/write locks in many places! I saw this post on StackOverflow quite some time back and really like the pattern that Marc has presented:

http://stackoverflow.com/questions/170028/how-would-you-simplfy-entering-and-exiting-a-readerwriterlock

In his answer he showed how you can simplify the code needed to enter a read lock, here’s the full implementation you can use in your project:

public static class ReaderWriterLockSlimExtensions
{
     private sealed class ReadLockToken : IDisposable
     {
          private ReaderWriterLockSlim _sync;
          public ReadLockToken(ReaderWriterLockSlim sync)
          {
               _sync = sync;
               sync.EnterReadLock();
          }
          public void Dispose()
          {
               if (_sync != null)
               {
                    _sync.ExitReadLock();
                    _sync = null;
               }
          }
     }
     private sealed class WriteLockToken : IDisposable
     {
          private ReaderWriterLockSlim _sync;
          public WriteLockToken(ReaderWriterLockSlim sync)
          {
               _sync = sync;
               sync.EnterWriteLock();
          }
          public void Dispose()
          {
               if (_sync != null)
               {
                    _sync.ExitWriteLock();
                    _sync = null;
               }
          }
     }

     public static IDisposable Read(this ReaderWriterLockSlim obj)
     {
          return new ReadLockToken(obj);
     }
     public static IDisposable Write(this ReaderWriterLockSlim obj)
     {
          return new WriteLockToken(obj);
     }
}

And to use it in your code, this is all you’ll need:

using (_sync.Read())
{
     // do reading here
}
using (_sync.Write())
{
     // do writing here
}

Further Readings:

Jon Skeet’s tutorial on Multi-Threading in .Net

Ayande has a post on using the UpgradeableReadLock