I'm making an abstract class that I need to validate fields in it's descendants. All the validated fields are marked by an attribute and are suppose to be checked for nulls or empty. To do that I get all the fields in the class:
var fields = this.GetType().GetFields().Where(field => Attribute.IsDefined(field, typeof(MyAttribute))).ToList();
And then, for every FieldInfo I try to do this:
if (string.IsNullOrEmpty(field.GetValue(this).ToString()))
{
// write down the name of the field
}
I get a System.NullReferenceException: object reference not set to an instance of an object.
I know I am suppose to pass the instance of a class to the GetValue method. But how can I pass the current instance (the one that's launching the logic)?
Or: Is there an other way of getting the field's value?
As Lucas says, the problem will be calling ToString()
when you shouldn't. Presumably your attribute should only be applied to string fields anyway, so the simplest approach is just to cast the result to string
. If that cast fails, it indicates a bigger bug (the attribute being applied incorrectly).
if (string.IsNullOrEmpty((string) field.GetValue(this)))
See more on this question at Stackoverflow