Bruno Peres Bruno Peres - 1 year ago 177
C# Question

Check if instance is a collection of given type

Let's say I have this dummy code:

var object1 = new Test();


So, if I need check if
object1
is an instance of
Test
class I can do:

var type = typeof(Test);
Console.WriteLine(object1.GetType() == type); // will print true


But now I have this
object2
(A list of
Test
objects):

var object2 = new List<Test>
{
new Test(),
new Test(),
new Test()
};


My question is: How can I check if
object2
is a list of
Test
instances?

Answer Source

what about?

  Type myListElementType = object2.GetType().GetGenericArguments().Single();
  if (myListElementType  == typeof(Test))
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download