Elisabeth
Elisabeth

Reputation: 21226

C#: Generic List Property

I am doing a UserControl where anyone can plugin a List.

Internally that List is sorted and programmatically added are the items to a internal ItemaSource.

Anyone who wants to use this UserControl must use the Property ElementsDataSource

public List<T> ElementsDataSource {get;set;}

List<T> is not working/compiling, instead I have to use List<object>.

But then I have to cast the objects inside the ElementsDataSource again to the generic type when I sort them internally and reuse them etc...

How can I offer a generic List Property to my user just like .NET is doing it?

Maybe my user is plugin in a List<Customer> or List<Department> etc... or am I totally wrong and should use List<Object> ?

Upvotes: 1

Views: 6030

Answers (3)

Migol
Migol

Reputation: 8447

If you don't want to make control class generic (this is your List<T> solution) then maybe you should try using List<ISomeInterface> that all classes used with this control implement?

Upvotes: 1

John Saunders
John Saunders

Reputation: 161831

Note that .NET uses IEnumerable or Object as the type of such a property. It then uses reflection to decide how to process the data.

Instead, you can require that your caller do any sorting or filtering, and just provide you a prepared IEnumerable.

If you need to be able to display a collection of objects, and the collection must be sorted within the control, and the collection must have a "natural" sort order, then the object should implement the IComparable<T> interface. You could then discover this through relection. You would be requiring that the collection implement both IEnumerable<T> and IComparable<T> so that you could do a "natural" sort on the items in the collection.

Upvotes: 0

Moo-Juice
Moo-Juice

Reputation: 38810

See: Making a generic property

Upvotes: 1

Related Questions