lundi 20 mars 2023

Getting value of Value Types in an class using reflection in C#

I wrote the following snippet to illustrate a scenario I faced and can't come up with the answer to the observed behavior:

public class X
{

    public string XS { get; set; }
    public int XN { get; set; }
    public MyEnum Enum { get; set; }
}

void testValueTypesReflectionComparison()
{
    var x1 = new X { XN = 1, XS = "argh", Enum = MyEnum.Component };
    var x2 = new X { XN = 1, XS = "argh", Enum = MyEnum.Component };

    var xTypeProperties = x1.GetType().GetProperties();
    foreach(var property in xTypeProperties)
    {
        var x1PropertyValue = property.GetValue(x1, null);
        var x2PropertyValue = property.GetValue(x2, null);

        if (x1PropertyValue != x2PropertyValue)
        {
            Console.WriteLine($"different values on property: [{property.Name}]: x1: [{x1PropertyValue}] x2: [{x2PropertyValue}]");
        }
    }
}

Output:

enter image description here

I could not spot anything in the docs that mention particularities in getting value types.
Why are reflected properties XN and Enum values different in x1 and x2 ?





Aucun commentaire:

Enregistrer un commentaire