I have a lot of unit tests that pretty much tests the same behavior. However, data type changes.
I am trying to create a generic method that can take any data type. I tried making my input parameter var but that’s not allowed. Also, looked into c# generics but that usually deals with a list.
You could make the parameter an
object:Or you could do what I prefer and make a generic method:
The generic approach has two major advantages, and I’ll give examples of why they’re useful:
arg, you still have access to it.Conversely, the
objectapproach has some important disadvantages:argas anobject, you’ll only be able to do things you could do with any object.objectparameter, the variable will be boxed, which means a performance hit. It’s not a huge hit, but if you callDoSomethingseveral thousand times in a row, you might start feeling it.Generics and Type Constraints
Adding a type constraint to a generic method allows you to restrict the method so that it only accepts certain types. Why is that useful? Because even though you don’t know—or care—what specific type you’re working with, you now know something about it, and you can use that information.
Consider the following setup:
Since we have an
IAnimalinterface, we can write generic methods targeting any implementation ofIAnimal:Run it: http://rextester.com/GOF1761
When we write the
DoMovemethod, we don’t care whether its parameteranimalis aDuck, aFish, anAnt, or anything else. All we care about is callinganimal.Move(). Since we used thewhere T : IAnimalconstraint, the compiler knows everything we need it to know:animalis of typeT.Tis, it implementsIAnimal.IAnimalhas aMove()method.animal.Move().(By the way, yes, we could just write
DoMoveasstatic void DoMove(IAnimal animal), but that’s another discussion.)Type Inference (and some of its implications)
Fine, but let’s take it a step further. In many cases, you can call generic methods without having to specify their type parameters. This is called type inference, and aside from saving you some typing, it can be useful when doing the same operation on objects of different types.
Run it: http://rextester.com/OVKIA12317
You only have to write the
DoMove<T>method once, and you can call it on any type ofIAnimalwithout having to give a more specific type. The appropriate version of Move will be called each time, becauseDoMove<T>is able to infer which type to use forT. When you callDoMove(duck), .NET understands that you really meanDoMove<Duck>(duck), which then calls theMovemethod on theDuckclass.