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?
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?
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;
}
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
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();
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];
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.