Skip Ribbon Commands
Skip to main content

Ondrej Sevecek's English Pages

:

Comments: Works unless one or both of o1 and o2 are not value types

Engineering and troubleshooting by Directory Master!
MCM: Directory

Sorry comments are disable due to the constant load of spam

2

Title

Works unless one or both of o1 and o2 are not value types

Author

Doug Kaye

Body

If you have

object o1 = new SomeObject();
object o2 = new AnotherObject();

then your solution will throw the following exception;

Microsoft.CSharp.RuntimeBinder.RuntimeBinderException
Operator '==' cannot be applied to operands of type 'ConsoleApp2.A' and 'ConsoleApp2.B'

The only universal solution I've found is using reflections. Just pass your objects to the following function;

        static new bool Equals(object o1, object o2)
        {
            System.Reflection.MethodInfo method = o1.GetType().GetMethod("Equals", new Type[] { o1.GetType() });
            if (method == null) method = o1.GetType().GetMethod("Equals");
            if (method != null)
            {
                return (bool)method.Invoke(o1, new object[] { o2 });
            }
            else
                return false;
        }

Attachments

Created at 28/09/2018 21:25 by  
Last modified at 28/09/2018 21:25 by