0

I wish to make a generic extension method :

public static IList<ValidationResult> ValidateMany<T>(this IValidator validator, IList objectsToValidate)
{
    var results = new List<ValidationResult>();
    foreach (var obj in objectsToValidate)
    {
        var validationResult = validator.Validate((T) obj);
        results.Add(validationResult);
    }
    return results;
}

I would like T to be passed in. That may seem easy by adding a template param, but then from the calling code I would like to do :

// calling code
var typeOfT = WorkOutTypeFromObjects(objectsToValidate);
var objectsToValidate = RowsToObjectsFactory.Create(typeName, tableRows);
var results = validator.ValidateMany<typeOfT>(objectsToValidate);

the top line there is the critical part that is hard to get, I need some dynamic way of working out the type and passing it in the T param. Or is there a good alternative?

sprocket12
  • 5,368
  • 18
  • 64
  • 133
  • Your `ValidateMany` method could be written as simply `objectsToValidate.Cast().Select(validator.Validate);` – Servy Jan 28 '15 at 15:48

1 Answers1

1

You can call the method using reflection. With the following extension-class

static class ValidatorExtension
{
    public static IList<ValidationResult> ValidateMany<T>(this IValidator validator, IList objectsToValidate)
    {
        var results = new List<ValidationResult>();
        foreach (var obj in objectsToValidate)
        {
            var validationResult = validator.Validate((T)obj);
            results.Add(validationResult);
        }
        return results;
    }
}

call the method like

    public void DoIt()
    {
        // Samplearray of type string
        var typeOfT = typeof(String);
        String[] objectsToValidate = new string[] { "AA", "BB" };

        MethodInfo methodInfo = typeof(ValidatorExtension).GetMethod("ValidateMany");
        MethodInfo genericMethod = methodInfo.MakeGenericMethod(new[] { typeOfT });
        IList<ValidationResult> forTheResult = new List<ValidationResult>();
        genericMethod.Invoke(forTheResult , objectsToValidate);
    }
black.rook
  • 41
  • 5