Question

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

Was it helpful?

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

OTHER TIPS

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

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))
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top