Jeremy
Jeremy

Reputation: 46322

c# casting question

If I have the following classes:

public class MyItems : List<MyItem>
{
..
}

public class MyItem : Item
{
..
}

How could I go about casting an instance of MyItems back down to List<Item>? I've tried doing an explicit cast and I get an exception.

Upvotes: 2

Views: 207

Answers (3)

Rodrick Chapman
Rodrick Chapman

Reputation: 5543

public class MyList : IList<MyClass>
{
    List<MyClass> _list;


    //Implement all IList members like so
    public int IndexOf(MyClass item)
    {
        return _list.IndexOf(item);
    }


    //Then help the type system a bit with these two static methods.
    public static implicit operator List<MyClass> (MyList mylist)
    {
        return mylist._list;
    }

    public static implicit operator MyList (List<MyClass> list)
    {
        return new MyList() { _list = list;}
    }

Upvotes: 0

Brian Mains
Brian Mains

Reputation: 50728

I believe I saw that was coming in 4.0. Not available yet.

Upvotes: 0

itowlson
itowlson

Reputation: 74802

You can't, because C# doesn't support generic variance (see here for discussion of terminology), and even if it did, it wouldn't allow this case, because if you could cast MyItems to List<Item>, you could call Add(someItemThatIsntAMyItem), which would violate type safety (because a MyItems can contain only MyItem objects, not arbitrary items).

See this question (or search SO for "c# generic variance") for additional information about this issue and future changes in C# 4 (though these will not affect your specific case).

Upvotes: 8

Related Questions