Here is my generic method code:
public static IT Activate<IT>(string path)
{
//some code here....
}
I'd want to set that generic IT must be only an interface.
Is this possible?
Generics make a class, interface and, method, consider all (reference) types that are given dynamically as parameters. This ensures type safety. Generic class parameters are specified in angle brackets “<>” after the class name as of the instance variable. Generic constructors are the same as generic methods.
Java Generic Interface In similar way, we can create generic interfaces in java. We can also have multiple type parameters as in Map interface. Again we can provide parameterized value to a parameterized type also, for example new HashMap<String, List<String>>(); is valid.
The actual type arguments of a generic type are. reference types, wildcards, or. parameterized types (i.e. instantiations of other generic types).
No, there's no such constraint in C#, or in .NET generics in general. You'd have to check at execution time.
if (!typeof(IT).IsInterface)
{
// Presumably throw an exception
}
No, you can't constraint IT
to any interface type and interface alone. The closest you have is the class
constraint and it applies to any class, interface, delegate, or array type.
- http://msdn.microsoft.com/en-us/library/d5x73970.aspx
The closest thing I can think of would be a runtime check in the static contructor. Like this:
static MyClass<IT>()
{
if(!typeof(IT).IsInterface)
{
throw new WhateverException("Oi, only use interfaces.");
}
}
Using the static contructor hopefully means it will fail fast, so the developer would discover the mistake sooner.
Also the check will only run once of each type of IT, not every method call. So won't get a performance hit.
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