How to differenciate a not assigned public int property new instance object from an assigned one

Lets have a simple class with an int property

    public class SimpleClass {
      public int myInt { get; set; }// for having a property and not "public int myInt;", see Jon Skeet remark

I instanciate it twice assigning myInt or not

    assignedObject = new SimpleClass() { myInt=0};
    notAssignedObject = new SimpleClass();

Now by reflection, I query the value of myInt in each case using

    Object value;

I am getting twice 0 for myInt, but I need to be able to differenciate them. How?

Jon Skeet

Unless you have code to specifically remember the difference between a property which has been initialized with its default value, and one which hasn't been set at all, you can't tell the difference. I have two suggestions, however:

  • You could make it an int? property, and then check whether the value is null. Of course, it's possible for it to be set to null explicitly, unless you prohibit that, but it may be good enough.
  • You could keep a separate bool value to know whether or not it's been set explicitly, and just set it in your property setter, along with the value.

Sample code for the second option:

public class SimpleClass
    private int value;
    private bool valueSet;

    public int Value
        get { return value; }
            this.value = value;
            this.valueSet = true;

    public bool ValueSet { get { return valueSet; } }


See more on this question at Stackoverflow