-1

What are the usages of a generic method in C# without using type argument as input parameters or return value?

private void method1<T>()

I have just explored in ASP.NET Core code and saw they have used this kind of generic method in a lot of places.

For example in UseMiddleware in UseMiddlewareExtensions.

public static IApplicationBuilder UseMiddleware<TMiddleware>(this IApplicationBuilder app,
    params object[] args)
{
    return app.UseMiddleware(typeof(TMiddleware), args);
}

Is it a common pattern or I am wrong?

AmirAdel
  • 35
  • 6
  • I'm not exactly clear what your question is. Can you clarify? Are you asking how to call `UseMiddleware`? What you have shown is an extension method for the `IApplicationBuilder` interface, so the method will appear as a member of any type that implements the interface. – Rufus L May 08 '20 at 22:37
  • Or maybe you are asking "why generic method can have the same name as non-generic one"? It's not clear where do you show example of "a generic method in C# without using type argument as input parameters"... – Alexei Levenkov May 08 '20 at 22:39
  • I'd say it's just idiomatic, it reads more naturally. It also saves the `typeof`. – Pac0 May 08 '20 at 22:42
  • This is an example: ```private void method1()``` I did not use T as return value or as a type of input parameters like this ```private T method1(T a)``` – AmirAdel May 08 '20 at 22:46
  • For anything you need to do without an instance, where you need to know the type. The difference is static type safety, as generics types need to be known at compile time, and the ability to use constraints – TheGeneral May 08 '20 at 22:52
  • 1
    But it *is* a kind of input parameter... specifically, you're passing in the type itself. Of course, you can't use it in that form, hence the `typeof` call on it. – Powerlord May 08 '20 at 22:58
  • If that didn't exist, then in your ASP.NET `Configure` method, you'd have to call `app.UseMiddleware(typeof(MyMiddleware))` instead of `app.UseMiddleware()` ; this is sort of a bad example as most middlewares have their own Use functions that call this internally, such as `app.UseAuthentication()` or `app.UseStaticFiles()` – Powerlord May 08 '20 at 23:01
  • May my post could be related to this: https://stackoverflow.com/questions/10955579/passing-just-a-type-as-a-parameter-in-c-sharp – AmirAdel May 08 '20 at 23:13

1 Answers1

0

It's just a way of passing in a Type, instead of adding an extra Type parameter. It's exactly the same as:

public static IApplicationBuilder UseMiddleware(this IApplicationBuilder app,
    params object[] args,
    Type middlewhereType)
{
    return app.UseMiddleware(middlewhereType, args);
}

It's just a matter of stylistic choice, which one to use.

JoelFan
  • 37,465
  • 35
  • 132
  • 205