How to use the "is" operator in System.Type variables?

that's what I'm doing:

object ReturnMatch(System.Type type) { foreach(object obj in myObjects) { if (obj == type) { return obj; } } } 

However, if obj is a subclass of type , it will not match. But I would like the function to return just as if I were using the is operator.

I tried the following, but it will not compile:

 if (obj is type) // won't compile in C# 2.0 

The best solution I came up with was:

 if (obj.GetType().Equals(type) || obj.GetType().IsSubclassOf(type)) 

Is there a way to use the is operator to clear code?

+3
c #
Sep 16 '08 at 13:44
source share
5 answers

I used the IsAssignableFrom method, having encountered this problem.

 Type theTypeWeWant; // From argument or whatever foreach (object o in myCollection) { if (theTypeWeWant.IsAssignableFrom(o.GetType)) return o; } 

Another approach that may or may not work with your problem is to use a generic method:

 private T FindObjectOfType<T>() where T: class { foreach(object o in myCollection) { if (o is T) return (T) o; } return null; } 

(Code written from memory and not verified)

+4
Sep 16 '08 at 13:59
source share

maybe

 type.IsAssignableFrom(obj.GetType()) 
+2
Sep 16 '08 at 13:47
source share

Do not use the is operator, but the Type.IsInstanceOfType method seems to be what you are looking for.

http://msdn.microsoft.com/en-us/library/system.type.isinstanceoftype.aspx

+2
Sep 16 '08 at 13:56
source share

the is statement indicates whether it will be "safe" to pour one object as another obeject (often a superclass).

 if(obj is type) 

if obj is of type "type" or its subclass, then the if statement will succeed because it is "safe" to cast obj as (type) obj.

see: http://msdn.microsoft.com/en-us/library/scekt9xw(VS.71).aspx

0
Sep 16 '08 at 13:48
source share

Is there a reason you cannot use the keyword "eat"?

 foreach(object obj in myObjects) { if (obj is type) { return obj; } } 

EDIT. I see what is missing. Isak's suggestion is correct; I tested and confirmed this.

  class Level1 { } class Level2A : Level1 { } class Level2B : Level1 { } class Level3A2A : Level2A { } class Program { static void Main(string[] args) { object[] objects = new object[] {"testing", new Level1(), new Level2A(), new Level2B(), new Level3A2A(), new object() }; ReturnMatch(typeof(Level1), objects); Console.ReadLine(); } static void ReturnMatch(Type arbitraryType, object[] objects) { foreach (object obj in objects) { Type objType = obj.GetType(); Console.Write(arbitraryType.ToString() + " is "); if (!arbitraryType.IsAssignableFrom(objType)) Console.Write("not "); Console.WriteLine("assignable from " + objType.ToString()); } } } 
0
Sep 16 '08 at 13:54
source share



All Articles