user1977936
user1977936

Reputation: 31

Cast KeyValuePair to Interface

I'm having a problem of InvalidCastException trying to cast an

IList<KeyValuePair<string, object>> x

to an

IList<IItem> y

where IItem is my interface I have tried...

IList<IItem> y = (IItem) x; //INVALIDCASTEXCEPTION

IList<IItem> y = x.Cast<IItem>().ToList(); //another exception

... someone can help me?

Upvotes: 0

Views: 2347

Answers (3)

Tim Schmelter
Tim Schmelter

Reputation: 460288

A KeyValuePar<string,object> cannot be casted to your interface. You need to create instances of a class which implements it, then you can cast it to the interface type.

Assuming this is your interface and a class which implements it:

interface IItem
{
    string Prop1 { get; set; }
    object Prop2 { get; set; }
}

class SomeClass : IItem
{
    public string Prop1
    {
        get;
        set;
    }

    public object Prop2
    {
        get;
        set;
    }
}

Now you can create a IList<IItem> from your List<KeyValuePar<string,object>>:

IList<KeyValuePair<string, object>> xList = ...;
IList<IItem> y = xList
    .Select(x => (IItem)new SomeClass { Prop1 = x.Key, Prop2 = x.Value })
    .ToList();

Upvotes: 2

Netfangled
Netfangled

Reputation: 2081

You could define a cast to IItem yourself using the explicit keyword, or the implicit keyword

Upvotes: -1

e_ne
e_ne

Reputation: 8469

KeyValuePair<TKey, TValue> doesn't implement IItem, which doesn't seem to be even part of the .NET Framework. You can't cast it, unless you've redefined KeyValuePair somewhere.

EDIT: even if you had your interface defined, you couldn't cast an IList<YourKeyValuePair> to IList<IItem> because IList is not covariant. You could cast it to an IEnumerable<IItem>, however.

Upvotes: 1

Related Questions