Home > database >  Is there a way to know if object property value is already set or is it default?
Is there a way to know if object property value is already set or is it default?

Time:05-19

I am looking for a way to find out if object property value is already set or if it's still default. My class:

class TestModel
{
    public string TestStringProperty { get; set; }
    public int TestIntProperty { get; set; }
    public bool TestBoolProperty { get; set; }
}

and I initialize it:

TestModel model = new()
{
    TestBoolProperty = false,
    TestStringProperty = "testValue",
    TestIntProperty = 1,
};

Later I run this code, to get current and default values for those properties:

foreach (PropertyInfo propertyInfo in model.GetType().GetProperties())
{
    object? currentValue = model.GetType()?.GetProperty(propertyInfo.Name)?.GetValue(model, null);
    object? defaultValue = propertyInfo.GetValue(Activator.CreateInstance(dummyModel.GetType()), null);
    Trace.WriteLine($"Current value for property {propertyInfo.Name} is: {currentValue?.ToString()}");
    Trace.WriteLine($"Default value for property {propertyInfo.Name} is: {defaultValue?.ToString()}");
}

and the output is:

Current value for property TestStringProperty is: testValue
Default value for property TestStringProperty is: 
Current value for property TestIntProperty is: 1
Default value for property TestIntProperty is: 0
Current value for property TestBoolProperty is: False
Default value for property TestBoolProperty is: False

However, TestBoolProperty (bool) value is the same as default value (false). If I hadn't initialized it, it would still be default.

My question: Is there a way to find out if this property is set, even if its value the same as default?

CodePudding user response:

Use backing fields and a boolean value:

class TestModel
{
    private string _testStringProperty;
    private bool _testStringPropertySet;

    public string TestStringProperty
    {
        get { return _testStringProperty; }
        set { _testStringProperty = value; _testStringPropertySet = true; }
    }

Then you can check the boolean field in addition to the property value.

CodePudding user response:

As far as I know there's no way to tell the difference between a default value and an assigned value if that value is the same as the default. @DiplomacyNotWar provided a way around that. Another option is to use Nullable and check the HasValue property. This will be null until the field is set (or if it was set to null explicitly).

  • Related