~/src/www.mokhan.ca/xlgmokha [main]
cat returning-the-default-on-generic-types.md
returning-the-default-on-generic-types.md 3573 bytes | 2007-05-18 00:00
symlink: /opt/dotnet/returning-the-default-on-generic-types.md

Returning the Default on Generic Types

So during my quest to understand NHibernate I came across a new keyword in C#.

Here’s my problem… When you define a generic type it does not assume it to be either of a reference type or value type. And I do not want to force my type to be a reference type, I want it to be generic. But in a scenario where I have to return an blank or “null” value, that assumption says that the type has to be a reference type…

Here’s what I’m talking about:

The return null statement is making the assumption that T is a reference type. (I don’t want to make this assumption!) In this case I would like to return the default value for reference types and value types without having to create 2 generic types. One for each!

So I can use the default(T) statement which will return a null for reference types, and a 0 for value types! Problem solved.

public T SearchFor(Int32 id)
{
  using(ISessionTransaction dbStore = _manager.StartTransaction())
  {
    try
    {
      return (T)dbStore.Session.Load(typeof(T), id);
    }
    catch(ObjectNotFoundException)
    {
      return default(T);
    }
    catch(ADOException)
    {
      if (dbStore != null && null != dbStore.Transaction)
      {
        dbStore.Transaction.Rollback();
        throw;
      }
    }
  }
}

See MSDN for more information… http://msdn2.microsoft.com/en-us/library/xwth0h0d(VS.80).aspx