tags:

views:

136

answers:

2

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

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 have stripped the implementation to simplify it (I actually use a real object, not the IMetadataType declared here).

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

What am I missing?

+1  A: 

How is the .Add method declared?

Ok, if the .Add method expects a TMetadata, you can't expect it to take a IMetadataType, since you say that TMetadata is a IMetadataType, not the other way around.

Basically, for all the compiler knows, you can be trying to add something entirely different than a TMetadata, and the fact that you implement a common interface doesn't matter.

Lasse V. Karlsen
Sorry, the "Values" property is a dictionary of type <TMetadata, TData>.
Carl
Thanks. You mean I still can't do this even though the Metadata class also has the same where clause on the class?
Carl
+1  A: 

The where TMetadata : IMetadataType is a constraint for the generic type parameter TMetadata saying it should derive from IMetadataType. Since oMetadata knows only TMetadata and TData as types to work with, you have to use them in your methods body. This should work:

private void FillMetadata<TMetadata, TData>(Metadata<TMetadata, TData> oMetadata) 
    where TMetadata : IMetadataType
{
    TMetadata o;
    oMetadata.Values.Add(o, (TData)(object)GetValue());
}
Prensen
I see the problem now. What I'm trying to do is like trying to add a base class object to a list of derived class objects, right? Obviously, that doesn't work.
Carl