vratojr
vratojr

Reputation: 835

C# get property value with reflection has not default value

I have this code:

messageDto = new CorrelationDto()
{
timestamp = default,
};

var isDefault = messageDto.GetType().GetProperty("timestamp").GetValue(messageDto) == default; // FALSE
var isDefault2 = messageDto.timestamp == default; // TRUE

where timestamp is a DateTime.

As you can see, getting the value through reflection and comparing to default return false. Do you have any idea why it's happening and how should I do to check for default values? Thanks

== EDIT ==

It has been pointed to me that the return value of GetValue() is an object and so it must be casted to DateTime in order for the default to work. Unfortunately I cannot because I'm running this test on all the properties of an object to discover if this object is initialized or not (so I check for null or default value). And the messageDto in reality is a generic type so I don't know the types of its properties a priori.

Upvotes: 0

Views: 872

Answers (2)

User
User

Reputation: 96

If I correctly understood you, this is how I solved this problem:

    private static bool IsValueNumericDefault(object value)
    {
        var intVal = 1;
        var doubleVal = 1.0;

        return (int.TryParse($"{value}", out intVal) || double.TryParse($"{value}", out doubleVal)) && 
               (intVal == default || doubleVal == default);
    }

I check random object value through casting it to string and try parse to type that I check. Value parameter is returned by reflection method .GetValue(). You can try to parse it to DateTime or any other type that you check.

Upvotes: 0

Joe Sewell
Joe Sewell

Reputation: 6610

GetValue returns an object of type object, because it can't know at compile time what the type of the property is. The default value of an object is null, but since DateTime is a value type, its default value cannot be null.

Cast the result of GetValue to DateTime.

Upvotes: 5

Related Questions