Compile error using generic method in C #

EDIT: I found out that I can compile it if I pass the IMetadataType object to the TMetadata type. Why do I need it?

EDIT # 2: The "Values" property is a .NET dictionary of type <TMetadata, TData>.

I have this generic method:

private void FillMetadata<TMetadata, TData>
    (Metadata<TMetadata, TData> oMetadata) where TMetadata : IMetadataType
{
    IMetadataType o;
    oMetadata.Values.Add(o, (TData)(object)GetValue());
}

      

I've removed the implementation to keep it simpler (I'm actually using the real object, not the IMetadataType declared here).

My question is, why doesn't this compile? Compile error in Add () method: "Cannot convert from" IMetadataType "to" TMetadata ". Isn't that what the where clause for the method?

What am I missing?

0


source to share


2 answers


where TMetadata : IMetadataType

is a constraint on a type parameter TMetadata

saying it should be inferred from IMetadataType

. Since he oMetadata

only knows TMetadata

and TData

how types to work, you should use them in your method. This should work:



private void FillMetadata<TMetadata, TData>(Metadata<TMetadata, TData> oMetadata) 
    where TMetadata : IMetadataType
{
    TMetadata o;
    oMetadata.Values.Add(o, (TData)(object)GetValue());
} 

      

+1


source


How is the .Add method declared?

Well, if the .Add method expects TMetadata, you cannot expect it to accept an IMetadataType, since you are saying that TMetadata is an IMetadataType and not the other way around.



Basically, for everything the compiler knows, you can try adding something completely different than TMetadata, and the fact that you are implementing a generic interface doesn't matter.

+1


source







All Articles