-3

How can I use the is keyword with an object, rather than an object's class?

Here is some code:

private bool IsObjectCompatableWithObjects(object obj, IEnumerable<object> objects)
{
    foreach (var item in objects)
    {
        if (obj is item)
        {
            return true;
        }
    }
    return false;
}

The above code has the following error:

The type or namespace name 'item' could not be found (are you missing a using directive or an assembly reference?)

RobIII
  • 8,488
  • 2
  • 43
  • 93
Simon
  • 7,991
  • 21
  • 83
  • 163

3 Answers3

0

I guess you're trying to achieve something like this?

private bool IsObjectCompatibleWithObjects(object obj, IEnumerable<object> objects)
{
    return objects.Any(i => i.GetType().IsAssignableFrom(obj.GetType()));
}

To test:

var objects = new object[] { 7, "foo", DateTime.Now, Guid.NewGuid() };

Console.WriteLine(IsObjectCompatibleWithObjects(1, objects));
Console.WriteLine(IsObjectCompatibleWithObjects("test", objects));
Console.WriteLine(IsObjectCompatibleWithObjects(3f, objects));

Output:

True
True
False
RobIII
  • 8,488
  • 2
  • 43
  • 93
0

is is used against the type itself and NOT against the instance of type. So if you need to check if the item is of type object probably you should write -

if (item is Object)

instead of

 if (obj is item)

But then everything is object, so it is of little help. If you need to just check if the type if item in the list is same as type object, then you should do -

 if (item.GetType() == obj.GetType())
Yogi
  • 9,174
  • 2
  • 46
  • 61
0

If you want to see if your object is include in your enumerable of objects, you can use Enumerable.Contains from System.Linq:

Determines whether a sequence contains a specified element by using the default equality comparer.

You can use it like this:

private static bool IsObjectCompatableWithObjects<T>(T obj, IEnumerable<T> objects)
{
    return objects.Contains(obj);
}

Basically, you are doing something like this:

private static bool IsObjectCompatableWithObjects<T>(T obj, IEnumerable<T> objects)
{
    foreach (var item in objects)
    {
        if (obj.Equals(item))
        {
            return true;
        }
    }
    return false;
}

You can look for the exact implementation here.

aloisdg
  • 22,270
  • 6
  • 85
  • 105