How to make a method generic when "type 'T' must be a reference type"?

C#Generics

C# Problem Overview


> Possible Duplicate:
> Why do I get “error: … must be a reference type” in my C# generic method?

I have 2 Repository methods that are almost identical:

public IList<Fund> GetFundsByName(int pageSize, string searchExpression)
{
    return _session.CreateCriteria<Fund>()
        .AddNameSearchCriteria<Fund>(searchExpression)
        .AddOrder<Fund>(f => f.Name, Order.Asc)
        .SetMaxResults(pageSize).List<Fund>();
}

public IList<Company> GetCompaniesByName(int pageSize, string searchExpression)
{
    return _session.CreateCriteria<Company>()
        .AddNameSearchCriteria<Company>(searchExpression)
        .AddOrder<Company>(f => f.Name, Order.Asc)
        .SetMaxResults(pageSize).List<Company>();
}

The only difference is that the first one's _session.CreateCriteria is of type Fund and the second one is company

I was hoping that I could make this generic by changing the method definition to:

public IList<T> GetEntitiesByName<T>(int pageSize, string searchExpression)
    where T : ISearchableEntity
{
    return _session.CreateCriteria<T>()
        .AddNameSearchCriteria<T>(searchExpression)
        .AddOrder<T>(f => f.Name, Order.Asc)
        .SetMaxResults(pageSize).List<T>();
}

where ISearchableEntity is defined as:

public interface ISearchableEntity
{
    string Name { get; set; }
}

but unfortunately NHibernate doesn't like this and gives me the error:

The type 'T' must be a reference type in order to use it as parameter 'T' in the generic type or method 'NHibernate.ISession.CreateCriteria<T>()'

Is it possible for me to make this generic some other way?

C# Solutions


Solution 1 - C#

You could try adding the constraint class:

where T : class, ISearchableEntity

Solution 2 - C#

Here's the full list of constraints you can use on T

http://msdn.microsoft.com/en-us/library/d5x73970.aspx

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionDaveDevView Question on Stackoverflow
Solution 1 - C#Mark ByersView Answer on Stackoverflow
Solution 2 - C#theburningmonkView Answer on Stackoverflow