Reputation: 1373
here is what a 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 the same way as if I was using the operator is
.
I tried the following, but it won't 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))
Isn't there a way to use operator is
to make the code cleaner?
Upvotes: 5
Views: 2856
Reputation: 9857
Is there a reason why you cannot use the "is" keyword itself?
foreach(object obj in myObjects)
{
if (obj is type)
{
return obj;
}
}
EDIT - I see what I was missing. Isak's suggestion is the correct one; I have tested and confirmed it.
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());
}
}
}
Upvotes: 0
Reputation: 35884
I've used the IsAssignableFrom method when faced with 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 is not tested)
Upvotes: 5
Reputation: 7549
Not using the is operator, but the Type.IsInstanceOfType Method appears to be what you're looking for.
http://msdn.microsoft.com/en-us/library/system.type.isinstanceoftype.aspx
Upvotes: 3
Reputation: 47873
the is operator indicates whether or not it would be 'safe' to cast one object as another obeject (often a super class).
if(obj is type)
if obj is of type 'type' or a subclass thereof, then the if statement will succeede as it is 'safe' to cast obj as (type)obj.
see: http://msdn.microsoft.com/en-us/library/scekt9xw(VS.71).aspx
Upvotes: 0