Common Interfaces

Here is my code

public interface ITranslator<E, R> { E ToEntity<T>(R record); } class Gens : ITranslator<string, int> { #region ITranslator<string,int> Members public string ToEntity<MyOtherClass>(int record) { return record.ToString(); } #endregion } 

When I compile this, I get the error Type parameter declaration must be an identifier not a type

Why can't I have ToEntity<MyOtherClass> , but can only have ToEntity<T> ??

Edit: What does MyOtherClass do? I convert between objects (the equivalent of POCOs for the Entity platform) and the record (Object returned by the infrastructure) for several tables / classes. Therefore, I would like to use this to perform class specific conversion

+6
generics c # interface
source share
3 answers

Your interface has a generic ToEntity<T> method that you added to your Gens implementation class as a generic Gens class, like ToEntity<MyOtherClass> . (The generic method can accept any type parameter, possibly with certain restrictions on T Your Gens class tries to provide a definition for ToEntity only for a parameter of type MyOtherClass , which defeats the generics target.)

In your code example, it is not clear how your Gens class is trying to use the MyOtherClass type; he, of course, is not involved in ToEntity logic. We need additional information to be able to take you further.

To illustrate here what your current ITranslator<E, R> interface definition offers in plain English:

"I provide a mechanism for translating any record of type R into an object of type E , this mechanism is dependent on any user type T "

Your Gens class, on the other hand, the way it is being developed, "implements" the above interface as follows:

"I can translate integers into strings. I give the illusion of allowing the user to specify the type of control how this translation is performed, but there really is no choice. The MyOtherClass class is MyOtherClass involved; that is all I can say."

It can be seen from these two descriptions that the Gens class does not fulfill what the ITranslator<E, R> interface guarantees . Namely, he does not want to accept the type specified by the user for his ToEntity method. That is why this code will not compile for you.

+9
source share

You must declare a constraint for the generic type.

 public string ToEntity<T>(int record) where T : MyOtherClass 
+2
source share

This compiles for me in LINQpad. Perhaps you have a type named E, R or T somewhere?

Ahh I see what you are trying to do ... you have MyOtherClass defined as a class, but you are trying to use it as a type argument in ToEntity. How exactly do you want MyOtherClass to participate in ToEntity?

+1
source share

All Articles