I have an interface called Identifiable<TId>
that contains a single property Id of the given type. I want to create a generic class that takes one of these as a type parameter. It should be generic because I want to return concrete type, call other generic methods from within it and use things like typeof(T)
.
This works fine:
public class ClassName<T, TId> where T : Identifiable<TId>
Problem is that calling code has to pass in two types. eg. new ClassName<Person, int>()
I am wondering if in .net 3.5 there is some way to write this so that TId could be inferred by T? Allowing the caller to just do new ClassName<Person>()
?
Yes, you can pass Interface as a parameter in the function.
1. A class that implements a generic interface MUST be generic. If implementing class of generic interface is not generic, there will be a compile-time error because the parameterized type is not known.
Whenever you want to restrict the type parameter to subtypes of a particular class you can use the bounded type parameter. If you just specify a type (class) as bounded parameter, only sub types of that particular class are accepted by the current generic class.
From the nature of your question, I'm guessing that your ClassName doesn't rely on any methods in Identifiable that require TId (otherwise you would need the type.) If that's the case, one common solution in this case is to create a non-generic base interface, with all of the methods that don't require the TId type. Then you have:
interface Identifiable<TId> : Identifiable //Not a standard interface name, btw
and your constraint becomes:
public class ClassName<T> where T : Identifiable
Assuming that you actually do need the TId type, but are just looking to simplify the construction syntax, one option, if your constructor is taking an instance of the Identifiable (such as Person in your example) is to change the constructor to a factory method:
public static ClassName<T, TId> FromIdentifiable<T,TId>(T identifiable) where T: Identifiable<TId>
The above should allow the compiler to infer the types and give you a shorter syntax, based on the type of the parameter.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With