6

I've got a observable collection of objects of few known types, but when iterate on them I do not know the type of the current object.

How can I get the type of current object?

Mp0int
  • 18,172
  • 15
  • 83
  • 114
Paweł Bała
  • 63
  • 1
  • 5

5 Answers5

1

To get a type of an object at runtime you should call GetType() . If you know the objects can be of just a few known types you can use a switch statement:

Type t = obj.GetType();

switch (t.Name)
{
    case "Int32":
        Console.WriteLine("int type");
        break;
    case "String":
        Console.WriteLine("string type");
         break;
    default:
        Console.WriteLine("Another type");
        break;
}
w.b
  • 11,026
  • 5
  • 30
  • 49
0

You have to use the GetType Method, as described here GetType

Object.GetType()

If you have known types, you can check them with the typeof(object), as described here: typeof

Stefano Bafaro
  • 915
  • 10
  • 20
0

You can use GetType method. Like this:

ObservableCollection<object>  coll = new ObservableCollection<object>();

    var a = this.coll[0].GetType();
    var b = this.coll[1].GetType();
Valentin
  • 5,380
  • 2
  • 24
  • 38
0

In case you have an ObservableCollection which has a generic type you can write something like this to get to know what's in it:

// Assume this is your observable collection
var observableCollection = new ObservableCollection<string>();
Type type = observableCollection.GetType().GetGenericArguments()[0];
Corstian Boerman
  • 848
  • 14
  • 32
0

If there are only a few different types and you're taking a different action depending on the type then you can use is to check each type:

foreach(var thing in collection){
    if(thing is TypeA){
        doTypeA();
    }else if(thing is TypeB){
        doTypeB();
}

Another possible option, if it makes design sense and the objects are under your control, is to have them all implement an interface which includes a method to get an Enum describing the type? Then you can switch on that.

LexyStardust
  • 1,018
  • 5
  • 18