Home > Mobile >  Are there any issues with having a non-generic method in a generic class?
Are there any issues with having a non-generic method in a generic class?

Time:06-19

On MSDN (https://docs.microsoft.com/en-us/dotnet/standard/generics/), it says:

Generic methods can appear on generic or nongeneric types. It is important to note that a method is not generic just because it belongs to a generic type, or even because it has formal parameters whose types are the generic parameters of the enclosing type. A method is generic only if it has its own list of type parameters. In the following code, only method G is generic.

Isn't M for all intents and purposes generic? If you call method M on some instance of type T, M can only have input and output parameters of type T. Would there be any issues with using such a nongeneric method M?

class A
{
    T G<T>(T arg)
    {
        T temp = arg;
        //...
        return temp;
    }
}
class Generic<T>
{
    T M(T arg)
    {
        T temp = arg;
        //...
        return temp;
    }
}

CodePudding user response:

Isn't M for all intents and purposes generic?

If you use reflection to inspect those methods, you'll find that IsGenericMethod and IsGenericMethodDefinition are true for A.G, and false for Generic<>.M. This is true even though Generic<>.M's return type is T, whose IsGenericParameter property is true.

You're asking a question about semantics (i.e. the linguistic meaning of "generic method"), and Microsoft has defined the meaning of these concepts as they pertain to C#. So when Microsoft says that a generic method is one that takes generic type arguments, that's the definition that's going to be accepted, both by developers and by the framework itself.

If you call method M on some instance of type T, M can only have input and output parameters of type T.

Yes, the difference is in the scope of the type T. For example, if you have an instance of Generic<string>, you cannot pass its M an int. With the generic method, the generic arguments can be changed at the method level, whereas a non-generic method on a generic class uses types that match the generic types of the class that it belongs to.

Would there be any issues with using such a nongeneric method M?

There are no "issues" with using a non-generic method like M inside of a generic class. That's how generic classes were meant to work. Just be aware of the differences in behavior I mentioned above.

  • Related