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?
The is operator is used to check if the run-time type of an object is compatible with the given type or not. It returns true if the given object is of the same type otherwise, return false. It also returns false for null objects.
static bool IsFirstFridayOfOctober(DateTime date) => date is { Month: 10, Day: <=7, DayOfWeek: DayOfWeek.Friday }; In the preceding example, the is operator matches an expression against a property pattern with nested constant and relational (available in C# 9.0 and later) patterns.
The is operator returns true if the given object is of the same type, whereas the as operator returns the object when they are compatible with the given type. The is operator returns false if the given object is not of the same type, whereas the as operator returns null if the conversion is not possible.
The GetType method is inherited by all types that derive from Object. This means that, in addition to using your own language's comparison keyword, you can use the GetType method to determine the type of a particular object, as the following example shows.
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)
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
Perhaps
type.IsAssignableFrom(obj.GetType())
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With