Click here to Skip to main content
15,884,425 members
Articles / Programming Languages / C#
Alternative
Tip/Trick

Is operator working simulation

Rate me:
Please Sign up or sign in to vote.
5.00/5 (2 votes)
12 Jul 2011CPOL 6.2K   1
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)


Written By
Austria Austria
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.

Comments and Discussions

 
GeneralAppreciate your suggestion, but as said i am not creating a ... Pin
zenwalker198515-Jul-11 1:32
zenwalker198515-Jul-11 1:32 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.