Statically determine type of Collection

  • Thread starter Thread starter cody
  • Start date Start date
C

cody

Hi!

we are building an xml-export tool to export our business entities from
out app. we use reflection to determine the data type of properties.

e.g. we have a class Customer with a CustNo property, and reflection
tells us that the type is int. so far so good.

Now we have a ContactCollection (which inherits from MyBaseColletion)
inside the Customer class.

How can we determine the type of the list, that is, the type of the
elements inside the list? We could check the return type of the indexer
for example, but what if the list doesn't have any? Is there another way
to determine the element type or at least enforce the programmer to
provide an indexer?

Note that we do not have instance of the classes at the timer the export
is configured, that is somebody chooses which fields and how deep the
export should go. Even if we had an instance at that time, if the
collection would be empty then we also do not see the type if its contents.

The only thing I could think of where a static abstract property say,
GetElementType which must be overridden in each class (I know that this
is not possible).

I came across a similar problem when trying to attach static data to
classes for a data access layer a few week ago.
Am I missing something???
 
is this 1.1 or 2.0? If 2.0 you could simply make your collections implement
IList<T>, IEnumerable<T> or similar (perhaps even by using Collection<T> or
List<T> as the base) - you then have a lot of power to look at T (code
below) - and it isn't even using reflection; you could also define (on a
base-class) an indexer typed as T, so ContactCollection :
BaseCollection<Contact> would automatically have an indexer of type Contact.

Marc

using System;
using System.Collections.ObjectModel;
using System.Collections.Generic;
using System.Diagnostics;
class Contact {}
class Customer
{
public readonly Collection<Contact> Contacts = new
Collection<Contact>();
}
class Program
{
static void WhatType<T>(IEnumerable<T> data) {
Debug.WriteLine(typeof(T).FullName);
}
static void Main() {
Customer c = new Customer();
WhatType(c.Contacts);
}
}
 
Back
Top