C# – Why use a generic method with a type constraint instead of the type itself

cgenericsnet

In a different StackExchange question, I noticed someone using this prototype:

void DoSomething<T>(T arg) where T: SomeSpecificReferenceType
{
    //Code....
}

Bearing in mind there is only a single type constraint (SomeSpecificReferenceType), what is the difference and advantage of writing it like that, instead of simply:

void DoSomething(SomeSpecificReferenceType arg)
{
    //Code....
}

In both cases, arg will be subject to compile-time type checking. In both cases, the body of the method can safely rely on knowledge that arg is of (or is a descendant of) a specific type that is known at compile time.

Is this a case of an overzealous developer learning about generics before learning about ordinary inheritance? Or is there a legitimate reason why a method signature would be written this way?

Best Answer

Is this a case of an overzealous developer learning about generics before learning about ordinary inheritance?

Yes, it probably is.

Or is there a legitimate reason why a method signature would be written this way?

Maybe. Generally, it'd make more sense if there was a return value that involved T, or another parameter that used T.

But, it's possible that the internals of the code use T (perhaps as an argument to a serializer?) and need to use specifically T and not the constraint class. You'll occasionally see that when the constraint is an interface paired with the new constraint and the guts of the method creates Ts for some reason.

So while it's rare to see the constraint version needed, there are some times when it is. And it's always possible that the method used to need it, but now does not and the developer left it as is to not introduce a breaking change.