views:

116

answers:

8

Hi!

Is there any solution to solve the problem with this cast example? I need to add a new element to the collection, so I have to solve it.

    IEnumerable enumerable;
    IEnumerable enumerable2;
    enumerable = new ObservableCollection<Something>();
    enumerable2 = new ObservableCollection<Object>();


    ICollection<Object> try = (ICollection<Object>)enumerable;      //Don’t work
    ICollection<Object> try2 = (ICollection<Object>)enumerable2;    //Work
+2  A: 

Check out covariance and contravariance with generic parameters in C# 4. It might provide you with more information for future when faced with such problems.

Cheers,

Andrew

REA_ANDREW
A: 

If all you know is object, then the non-generic interfaces are your friend:

IList list = (IList)foo;
list.Add(yourItem);

However! Not all enumerable items are lists, so not all can be added in this way. IList underpins a lot of data-binding, so is a good bet.

Marc Gravell
A: 

"try" is a reserved word in C#. Have you tried another variable name? or you could use @try if you need to use the "try" variable name.

pymendoza
Sorry it's just a quick sample.:)
Wumpus
A: 

i'm not sure 100% that this is what you mean, but have you tried this:

        IEnumerable<Object> try3 = enumerable.Cast<Object>();

ok, it didn't work, how about dynamic typing:

        dynamic var = new Something();
        dynamic try1 = enumerable;      
        try1.Add(var);

regards

Kaneti

Kaneti
I tried it, but it doesn't work. And with this method I guess I get a new Collection, so I can't add a new element to the original (enumerable) collection.
Wumpus
edited for dynamic typing, does that do the trick?
Kaneti
glad to hear it worked.best of luck!
Kaneti
A: 

You can iterate through the something collection and insert the elements into the object one.

DanDan
A: 

Use the Cast extension combined with a ToList.

        IEnumerable ie1 = new ObservableCollection<string>();
        ICollection<object> ic1 = (ICollection<object>)ie1.Cast<object>().ToList();

Or iterate through manually.

Mart
A: 

If you have control over the relevant code, it is perhaps time to rethink the design a little. One often tries to use the most restricted interface possible that can still achieve the desired result. It seems in this case that IEnumerable cannot achieve that result, if one of the things you want to do is to add new items. Changing to a more appropriate type might be a better solution than having to cast the collection.

Lajnold
A: 

Dear Kaneti!

Dynamic typing works (Only one bad thing, that I have to link windows.csharp and system.core dlls, which are ~1MB, so it's not the best for a silverlight app, but It's the best solution, which I know now.)!

Many thanks!

P.S. Sorry I write so late, but I asked this question as unregistered user (Now I can't access the computer, which I used yesterday...), and it was difficult to register ;).

Wumpus