3

Possible Duplicate:
C# generic list <T> how to get the type of T?

This is a simple question. What is the most elegant and simple way to get the type of an ObservableCollection of unknown type?

I have a method:

public void DoSomething(object oc)
{
     //I know 'oc' is a ObservableCollection<T> 
     //How to get its type <T> without having to do
     //obj.GetType().GetProperties().....
}

Thanks

Community
  • 1
  • 1
Adolfo Perez
  • 2,834
  • 4
  • 41
  • 61

3 Answers3

1

You can pass the collection to a generic function

public static void AddUnknown<T>(this ObservableCollection<T> collection, object item){
      collection.Add((T)item);
}

That can then be used like collection.AddUnknown(obj)

if the compiler does not know which ObservableCollection you are using you will have to supply that information unless you are willing to use reflection

Rune FS
  • 21,497
  • 7
  • 62
  • 96
  • And do you know of a simple and elegant way to get the Type out of the collection? I tried this: ` public static T GetType(ObservableCollection collection) { return T; }` but I get an error saying Type parameter name not valid at this point. – Adolfo Perez Oct 24 '12 at 15:30
  • depends on what you meen by get it out. One way would be through GetGenericTypeArguments() – Rune FS Oct 24 '12 at 15:31
1

You can write an extension method that does it for you

public static Type GetGenericType<T>(this ObservableCollection<T> o)
{
    return typeof(T);
}

Have a look here as well: C# Get Generic Type Name

Edit:

This is very interesting :)

I came up with a solution that uses dynamic

public static void DoSomething(object o)
{
 var iCollection = o as ICollection;
 if(iCollection != null)
 {
    dynamic oc = iCollection;
    Type t = GetGenericType(oc); 
    // now you got your type :)
 }
}

public static Type GetGenericType<T>( List<T> o)
{
    return typeof(T);
}
Nasenbaer
  • 4,810
  • 11
  • 53
  • 86
flayn
  • 5,272
  • 4
  • 48
  • 69
  • The problem with this is that your sample method receives an observablecollection object. I need it to receive an object of object type which is an ObservableCollection but not explicitly... – Adolfo Perez Oct 24 '12 at 15:40
0

There are two ways, to work with the object:

  • using reflection (you told it is undesirable)
  • trial and error
  • using a base class or interface that is broad enough

Trial and error

Try all the variations, that you expect to be possible:

var list1 = oc as ObservableCollection<int>;
var list2 = oc as ObservableCollection<string>;
var list3 = oc as ObservableCollection<MyClass>;

if (list1 != null)
    list1.Add(1);

else if (list2 != null)
    list2.Add("str");

else if (list3 != null)
    list3.Add(new MyClass());

else
    throw new Exception("Unexpected object type.");

Using broad base class

 var list = oc as IList;
 list.Add(value);
Miguel Angelo
  • 23,796
  • 16
  • 59
  • 82