views:

179

answers:

2

I have a control mycontrol.ascx

This control has a property:

private GenericCollection<Item> myCollection;
public GenericCollection<Item> MyCollection
{
    get { return myCollection; }
    set { myCollection= value; }
}

Does anyone know how i could dynamically change from type Item to say type Product?

A: 

As you have specified C# 2.0 then I think the answer will be that you can't. C# is statically typed and this code types the generic collection to a collection of Item. If Product were a superclass of Item then I believe you could store them in this collection but you'd need to query the object type when you retrieved it from the collection as it'll always come back as an Item.

I'll throw a question back at you, what are you trying to achieve in this dynamic replacement and why? There may be a better answer.

EDIT

Thinking about it further, following the comment, you might be able to do it using an interface, i.e.:

public IList myCollection { get; set; }

I haven't tried it, away from my dev station but might spark some others to either agree or correct me :)

Lazarus
Thanks. MyControl.ascx is a Paging control that pages through collections. I want to have just one paging control in my site that accepts collections of various types.
Frawls
public IList myCollection Worked perfectly! Thants great. Cheers
Frawls
+1  A: 

You can't. One of the main ideas with generics is that they are type safe. If you want to be able to alter which type that is stored MyCollection, you will need to use some type from which both Item and Product are derived.

Fredrik Mörk