I have a FindAll method on my DataAccessLayer which looks like this:
public FindResult<T> FindAll<T>() where T : Entity, new()
and a client code that has a Type[] array which it needs to use to iteratively call the FindAll method with like this:
foreach (var type in typeArray)
{
var result = DataAccessLayer.FindAll<type>();
...
but the compiler complaints about "Type or namespace expected".. Is there an easy way to get around this? I've tried type.GetType() or typeof(type) and neither worked.
Many thanks in advance!
Generics in Java is similar to templates in C++. The idea is to allow type (Integer, String, … etc and user defined types) to be a parameter to methods, classes and interfaces. For example, classes like HashSet, ArrayList, HashMap, etc use generics very well. We can use them for any type.
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.
A generic method may be overloaded like any other method. A class can provide two or more generic methods that specify the same method name but different method parameters.
Constructing an Instance of a Generic TypeYou cannot create instances of it unless you specify real types for its generic type parameters. To do this at run time, using reflection, requires the MakeGenericType method.
You may need to use Reflection to do this, something like this:
DataAccessLayer.GetType().GetMethod("FindAll<>").MakeGenericMethod(type).Invoke()
This blog post may also contain the information you need.
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