Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Forcing user to use the right generic method in C#

Tags:

c#

.net

generics

It could be a silly question, but please help to answer it. Currently I have an interface with 2 generic methods:

ValidationResult Validate<T>(T t);


IList<ValidationResult> ValidateList<T>(IEnumerable<T> entities);

What I want is if you want to validate an object, use Validate method; if you want to validate an array of object, use ValidateList method, pretty clear in mind and interface. But it seems user can also use Validate method for a list of object without any compiler errors (of course!). Any there ways to restrict them to ValidateList method? Thank you so much.

like image 253
TuanHuynh Avatar asked May 06 '13 14:05

TuanHuynh


1 Answers

You can restrict a function to specific object types (and its derivatives) by doing something like this in the function declaration:

ValidationResult Validate<T>(T t) where T : ValidateBase, ValidateBaseOther

edit:

so in this case, the function will only take objects that are ValidateBase or its derivatives, or ValidateBaseOther or its derivatives. You can of course just use one if you want

ValidationResult Validate<T>(T t) where T : ValidateBase
like image 172
David S. Avatar answered Jan 03 '23 16:01

David S.