A generic api modification

In an attempt to become more comfortable with generics, I’m trying to find reasonable places to use them other than just for collections, etc.  This is one example:

I had a helper method that returns an object from nHibernate based on the supplied id:

public object GetObjectById(Type type, int id)

{

    if (this._activeSession != null)

    {

        return this._activeSession.Load(type, id);

    }

    else

    {

        throw new NullReferenceException(“The repository doesn’t have an active session”);

    }

}

Which I replaced with:

public T GetObjectById<T>(int id)

{

    if (this._activeSession != null)

    {

        return (T)this._activeSession.Load(typeof(T), id);

    }

    else

    {

        throw new NullReferenceException(“The repository doesn’t have an active session”);

    }

}

While it doesn’t really change anything for how the object is retrieved, it does simplify how I call the method.  Instead of having to write something like: 

Property property = MyHelperClass.GetObjectById(typeof(Property), id) as Property;

I instead write the following:

Property property = MyHelperClass.GetObjectById<Property>(id);

So in the future when I upgrade to nHibernate 1.2+, this should make the transition smoother.  nHibernate 1.2 supports generics among other things.

[Update] – I upgraded to nHibernate 1.2.  So my helper function looks like:

public T GetObjectById<T>(int id)

{

    if (this._activeSession != null)

    {

        return this._activeSession.Load<T>(id);

    }

    else

    {

        throw new NullReferenceException(“The repository doesn’t have an active session”);

    }

}