Reputation: 175
I'm writing a compare properties two objects of some class, for further listing differences.
Class oldObj, newObj;
//some initiation of above
Class classObject = new Class();
var objectKeys = classObject .GetType().GetProperties().ToList();
objectKeys.ForEach(key => {
var previousKeyValue = key.GetValue(oldObj);
var newKeyValue = key.GetValue(newObj);
if (!Equals) {...}
});
In special cases, newObj
or oldObj
can be nulls.
My problem is that, in such a case: key.GetValue(null)
I'm getting CS0120 exception - "Non-static method requires a target".
Looking at PropertyInfo options (from metadata):
public object? GetValue(object? obj);
I assumed that it will be able to handle such a situation with object being null
, with e.g. return null
as its value.
Could you please explain if this is proper behaviour of this code, or I'm making something wrong to use null? In such a case I would probably just before ForEach make some verification if objects are nulls and write separate compare code, handling this situation.
Upvotes: 2
Views: 910
Reputation: 33873
You are misunderstanding the nature of the parameter that is passed to GetValue()
.
When you pass in an object reference, it means that the reference is an instance property on an instance of an object. If you omit the object reference, you are telling the reflection api that you are trying to access a static member.
Upvotes: 1