Search code examples
c#.netreflectionfieldinfo

How do I compare FieldInfo's values of instances?


public partial class Form1 : Form
{        
    public Form1()
    {
        InitializeComponent();

        myClass instance1 = new myClass();
        myClass instance2 = new myClass();
        FieldInfo[] fields = typeof(myClass).GetFields();
        foreach (FieldInfo field in fields) if (field.GetValue(instance2) == field.GetValue(instance1)) Text = "Yes";           
    }
}

class myClass
{
    public bool b = false;
    public int i = 2;
}

Never returns "Yes".

EDIT: Without knowing beforehand what the types will be. So I can't have: (bool)field.GetValue(instance1).


Solution

  • You're using ==, which will be comparing the boxed values for any field where the type is a value type. Each time a value is boxed, it will create a new object, so == will never work like that. Use object.Equals instead:

     foreach (FieldInfo field in fields)
     {
         if (object.Equals(field.GetValue(instance2), field.GetValue(instance1))
         {
             Text = "Yes";
         }
     }
    

    (Using the static method here means it'll work even if the values are null.)