1

So I have a class that implements some concrete generic types. I also has an interface that is implemented by my class. I want to write an extension method that only works on the class if it is implement the generic base class and the interface, and if so resolve type arguments automatically. I tried the following so far:

Here is my extension method:

public static void AddValidationError<TEndpoint, TRequest, TResponse>(this TEndpoint endpoint, string property, string message)
    where TEndpoint: Endpoint<TRequest, TResponse>, IValidationError
    where TRequest: notnull
{
    var container = endpoint.Resolve<IValidationErrorContainer>();
    container.Errors.Add(new ValidationInfo(property, message));
}

Here is how I want to use it:

this.AddValidationError(nameof(myclass.Property1), "Message");

This is how it is possible to use it right now:

this.AddValidationError<{type of this}, {concreateT1}, {ConrateT1}>(nameof(myclass.Property1), "Message");

'this' implements Endpoint<(concreteT1), (concreteT1)> and IValidationError, so as you can see, I can figure out TEndpoint, TRequest, TResponse from the context, but I have to be explicit about this.

Is there any way to resolve the type argument without explicitly writing it out? I'm open to other approaches too!

  • This should work: `public static void AddValidationError(this Endpoint endpoint, string property, string message)` – Nin Jun 27 '23 at 08:53
  • Its not gonna work. The main point of generic TEndpoint parameter is to set constraints. As you can see i want to derive a class from endpoint base, and than if i need implement the interface. And after that i would like to use my extension method. It feel correct, but the compiler cant figure out the extension method generic parameters, so i have to set it manually and it works just fine. – Matyas Szekely Jun 29 '23 at 10:26
  • I guess i have to w8 for net8 and c# 12. i hope they deliver what they promised... – Matyas Szekely Jul 20 '23 at 21:00

0 Answers0