Home > Software design >  Passing generic type to non generic methods
Passing generic type to non generic methods

Time:10-06

I was wondering how to mix calls of specifically typed methods, when coming from a generically typed method?

I know the example given is redudant. It is for illustration purposes only. What I imagine would be a minimal comprehensive context would be as follow:

The method BitConverter.GetBytes has multiple overloads for value-types. But if I were to code a method that goes static byte[] GetBytes<T>(T value) where T : struct that would return BitConverter.GetBytes(value), I get an error message saying that the best overloaded match for has some invalid arguments.

I guess this has to do with value being of generic type instead of specific.

Is there any way to give generic types to non-generic methods ? Via some casting trick or anything ?

CodePudding user response:

It is not possible for now. you should costrain the generic type to something the compiler can narrow down to one of the overloads of the BitConverter.GetBytes(value). The struct you used to constrain is a very larger group than just one of the overloads, so it won't let you proceed.

With c#10 you might have one chance with the feature 'extend everything', but it's not yet released won't have much sense to talk about that now.

  • Related