In short, you cannot solve your problem (prevent IEnumerable<> from being passed to the general method) using generics. This is because you cannot have negative common constraints (i.e., Everything except someClass ). The only reason common restrictions exist is to let the compiler know what signature to expect for a generic type. It should not provide development-time hints to the developer.
In addition to any unspecified external requirements, you can define your general type in an interface, not in a method. This does not guarantee that T cannot implement IEnumerable<> ; however, it ensures that the ValidateList must accept a list of what is passed to Validate . This means that T can be an array, but this will force the ValidateList to accept an array of arrays.
If you leave generic types at the method level, although they both have a generic type named T , these types actually have nothing to do with each other.
A generic type defined in an interface.
public interface ISomeInterface<T> { ValidationResult Validate(T t); IList<ValidationResult> ValidateList(IEnumerable<T> entities); }
This will be implemented as:
public class SomeClass<T> : ISomeInterface<T> { ValidationResult Validate(T t) { // Do something ... } IList<ValidationResult> ValidateList(IEnumerable<T> entities) { // Do something ... } }
And used like this:
var myInstance = new SomeClass<int>(); int obj = 5; int arr = new [] {1,2,3}; myInstance.Validate(obj); myInstance.ValidateList(arr); myInstance.Validate(arr);
source share