Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to implement this interface generically so that it can be passed only one type parameter?

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>()?

like image 502
Adam Butler Avatar asked Nov 30 '11 21:11

Adam Butler


People also ask

Can we pass interface as a parameter to a method in Java?

Yes, you can pass Interface as a parameter in the function.

Can a generic class implement a non-generic interface?

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.

How do I restrict a generic type in Java?

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.


1 Answers

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.

like image 73
Dan Bryant Avatar answered Sep 23 '22 20:09

Dan Bryant