#539 – Type Inference When Calling Generic Methods
March 14, 2012 3 Comments
When you call a generic method, you can provide a type argument, indicating the type for any type parameters, or you can let the type be inferred by the compiler.
For the following type definition:
public static void DogBuriesThing<T>(Dog d, T thing)
You can either provide the type argument:
Dog buster = new Dog("Buster", 5); Dog.DogBuriesThing<Bone>(buster, new Bone("Buster's rawhide"));
Or you can omit the type when you call the method, letting the type be inferred based on the type of the second argument:
Dog.DogBuriesThing(buster, new Cow("Bessie"));
That’s one hungry dog to be burying an entire cow!
Not so hungry — it’s burying it for later.
Buster will live like a king for the foreseeable future.