wallah wallah - 1 year ago 90
C# Question

receive and use any type of ObservableCollection<T>

I met a trouble.

I want to receive any collection, type of ObservableCollection and use it.

For example, there is a class like following

public class Car{
int num;
string str;

and ObservableCollection

ObservableCollection<Car> carOC = new ObservableCollection<Car>();

The really important point is that actually I don't know the exist of it. I don't know what the type, T, of

What I want to make is a method for showing list of properties of received
like following

void showingProperties(ObservableCollection<T> coll)
foreach (T item in coll){
// showing item's property list

and if I use this method for


the output is

carOC has properties
num type int32
str type string

I don't know really anything to receive
and use it...
Thanks for reading it.

Answer Source

In fact your problem hasn't to do anything with an ObservableCollection<T>. You could do the same with any generic collection. Just for clarify, ObservableCollection<T> observes your list and items, so that it will give you information about changings in the List. It won't observe your class structure. It doesn't make much sense to do this on a List, because your T will exist serveral times in your list, but the Information will be the same for each object. So i would recommend a Method which give you such information for a type. See it type based not object based.

public string ShowProperties<T>() : where T : class
   var props = typeof (T).GetProperties(BindingFlags.Instance | BindingFlags.Public);

    string typeInfo = typeof (T).FullName + Environment.NewLine;
    foreach (var prop in props)
       typeInfo += prop.Name + " " + prop.PropertyType.FullName + Environment.NewLine;

  return typeInfo;

If you have different items in your List, because of inheritance call this serveral times in your foreach loop. But be carefull reflection is slow if you use it in loops. Think about caching then.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download