In Java I can have a method declaration something like this:
<T> List<T> getList(final Class<T> objectClass, String whatever)
Which means that I specify the list return type by specifying the Class to the method.
List<Customer> customers = getList(Customer.class, "blah");
And if I don’t specify the classes properly I get a compile time error. (which is what I’m looking for – I want the compiler to catch a mismatch).
List<String> customers = getList(Customer.class, "blah"); // will not compile
What’s the equivalent of this in C#?
TIA
There is no way in C# to have the compiler infer the generic type based on the return type.
In C#, you must specify T if the only differentiation is the return type:
This method would be written as:
However, in C#, type inference is automatically handled if there is a parameter that takes a type of customer. For example, you can have:
Then call this as (without
<Customer>):Edit in response to comment:
If you are going to be constructing a new “Customer” inside of your method, and want this to work on any type, you’ll need a new constraint in place. To have this:
You would need something like:
That being said, if you’re going to make a method like this, chances are you’ll also want to have a constraint to an interface, so you can setup the object you create:
This will let you use properties of
ISomeInterfacewithin the method, as well as limit it to only working with types that implement that interface.