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?
To construct a generic type from the generic type definition for a nested type, call the MakeGenericType method with the array formed by concatenating the type argument arrays of all the enclosing types, beginning with the outermost generic type, and ending with the type argument array of the nested type itself, if it ...
You can't inherit from a Generic type argument. C# is strictly typed language. All types and inheritance hierarchy must be known at compile time. . Net generics are way different from C++ templates.
The where clause in a generic definition specifies constraints on the types that are used as arguments for type parameters in a generic type, method, delegate, or local function. Constraints can specify interfaces, base classes, or require a generic type to be a reference, value, or unmanaged type.
Interface Type Constraint You can constrain the generic type by interface, thereby allowing only classes that implement that interface or classes that inherit from classes that implement the interface as the type parameter.
You could try adding the constraint class
:
where T : class, ISearchableEntity
Here's the full list of constraints you can use on T
http://msdn.microsoft.com/en-us/library/d5x73970.aspx
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With