So, I have a class that takes a parameter of a general type and does a little special processing if the type parameter is a subclass of the given type.
IEnumerable<T> models = ... // Special handling of MySpecialModel if (filterString != null && typeof(MySpecialModel).IsAssignableFrom(typeof(T))) { var filters = filterString.Split(...); models = from m in models.Cast<MySpecialModel>() where (from t in m.Tags from f in filters where t.IndexOf(f, StringComparison.CurrentCultureIgnoreCase) >= 0 select t) .Any() select (T)m; }
But I get an exception in the last line
Cannot convert type 'MySpecialModel' to 'T'
If I changed the code to use as instead of casting, I get this error.
The type parameter 'T' cannot be used with the 'as' operator because it does not have a class type constraint nor a 'class' constraint.
What am I missing here?
Update
This class can accept any type parameter, including struct and built-in types, so a general constraint would not be a suitable solution in my case.
source share