If i have:
public static Func<SomeType, bool> GetQuery() {
return a => a.Foo=="Bar";
}
and a generic version
public static Func<T, bool> GetQuery<T>() {
return (Func<T,bool>)GetQuery();
}
Is there a way to cast my strongly typed Func of SomeType to a Func of T? The only way I have found so far is to try and combine it with a mock function:
Func<T, bool> q=a => true;
return (Func<T, bool>)Delegate.Combine(GetQuery(), q);
I know how to do that with Expression.Lambda, but I need to work with plain functions, not expression trees
EDIT - using .net 3.5 Using Matthews examples, and with explicit detail of usage.
What I am after still though is how can I get from Func Of concreteType to Func Of T when returning a value.
I am just wanting to get past the compiler error - and am happy to have the potential for T to be a different type and throw a runtime error.
public interface ISecureEntity {
Func<T,bool> SecureFunction<T>(UserAccount user);
}
public class Product : ISecureEntity {
public Func<T,bool> SecureFunction<T>(UserAccount user) {
return (Func<T,bool>)SecureFunction(user); //this is an invalid cast
}
public static Func<Product,bool> SecureFunction(UserAccount user) {
return f => f.OwnerId==user.AccountId;
}
public string Name { get;set; }
public string OwnerId { get;set; }
}
public class ProductDetail : ISecureEntity {
public Func<T,bool> SecureFunction<T>(UserAccount user) {
return (Func<T,bool>)SecureFunction(user); //this is an invalid cast
}
public static Func<ProductDetail,bool> SecureFunction(UserAccount user) {
return pd => Product.SecureFunction(user)(pd.ParentProduct);
}
public int DetailId { get;set; }
public string DetailText { get;set; }
public Product ParentProduct { get;set; }
}
Then consumption in a repository:
public IList<T> GetData<T>() {
IList<T> data=null;
Func<T,bool> query=GetSecurityQuery<T>();
using(var context=new Context()) {
var d=context.GetGenericEntitySet<T>().Where(query);
data=d.ToList();
}
return data;
}
private Func<T,bool> GetSecurityQuery<T>() where T : new() {
var instanceOfT = new T();
if (typeof(Entities.ISecuredEntity).IsAssignableFrom(typeof(T))) {
return ((Entities.ISecuredEntity)instanceOfT).SecurityQuery<T>(GetCurrentUser());
}
return a => true; //returning a dummy query
}
}
Doo() as Func<T, bool>
it will compile... but it will still only work with Foo. – Matthew Whited