No, because the type argument must be known at compile time so that it appears in the source code.
You can either make BuilderInclusionsForm generic in the product type, or write a generic method like this:
private static T FindProduct<T>(T product) where T : Product { return db2.GetTable(typeof(T)) .OfType<T>() .SingleOrDefault(a => a.ProductID == p.ProductID); }
and then call it with reflection:
public BuilderInclusionsForm(Product p) : this() { MethodInfo method = typeof(BuilderInclusionsForm).GetMethod("FindProduct", BindingFlags.Static | BindingFlags.NonPublic); MethodInfo concrete = method.MakeGenericMethod(new Type[] { p.GetType() }); product = (Product) concrete.Invoke(null, new object[] { p }); }
(Obviously, you can cache the open form of the method.)
Not bad, but it should work. I suspect that it would be best to create a BuilderInclusionsForm, but you can always have a helper class:
public static class BuilderInclusionsForm { public static BuilderInclusionsForm<T> Create<T>(T product) where T : Product { return new BuilderInclusionsForm<T>(product); } }
which allows you to use type inference.
Jon skeet
source share