Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles / Languages / C#

Is operator working simulation

5.00/5 (2 votes)
12 Jul 2011CPOL 6.6K  
I think your function is no (theoretical) replacement for the is operator.The is operator takes an object (left) and a type (right) as arguments, not two objects.The is operator considers inheritance. Look at this (executable) example:using System;namespace IsOperatorCheck{ ...

I think your function is no (theoretical) replacement for the is operator.



  1. The is operator takes an object (left) and a type (right) as arguments, not two objects.
  2. The is operator considers inheritance. Look at this (executable) example:
  3. C#
    using System;
    
    namespace IsOperatorCheck
    {
        class Program
        {
            class Sample { }
            class Derived : Sample { }
    
            static void Main(string[] args)
            {
                Sample s = new Sample();
                Derived d = new Derived();
    
                Console.WriteLine(s is Sample);
                Console.WriteLine(d is Sample); // !!
                Console.WriteLine(IsOperatorCheck(s, d));
    
                Console.ReadKey();
            }
    
            static bool IsOperatorCheck(object arg1, object arg2)
            {
                bool result;
                if (arg1.GetType().IsValueType && arg2.GetType().IsValueType)
                    result = (arg1.GetType() == arg2.GetType());
                else
                    result = (arg1.GetType().Equals(arg2.GetType()));
                return result;
            }      
        }
    }


So maybe you should call your tip: "how to compare object types".

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)