2
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).

ispiro
  • 26,556
  • 38
  • 136
  • 291

3 Answers3

8

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.)

Jon Skeet
  • 1,421,763
  • 867
  • 9,128
  • 9,194
  • +1 Thanks. But I don't understand your comment about the static method. Do you mean as opposed to `field.GetValue(instance2).Equals(field.GetValue(instance1))`? – ispiro Feb 13 '12 at 23:31
  • @ispiro: Yes - that will throw a `NullReferenceException` if `field.GetValue(instance2)` returns null - whereas the static method won't. – Jon Skeet Feb 13 '12 at 23:33
0

you are comparing the address of the two objects returned by FieldInfo.GetValue and since those addresses in memory are different, the == is never true.

try replacing the if with this:

if (field.GetValue(instance2).Equals(field.GetValue(instance1)))
Davide Piras
  • 43,984
  • 10
  • 98
  • 147
  • as Jon suggested above, better to use object.Equals to avoid problems when the first FieldInfo.GetValue returns null. – Davide Piras Feb 13 '12 at 23:32
0

Because field.GetValue(instance1) returns a "boxed" (object) version of the value, hence calling == you are only comparing two different references.

Try instead calling:

field.GetValue(instance2).Equals(field.GetValue(instance1))
Maghis
  • 1,093
  • 1
  • 7
  • 15