I have a object which is used in another context and I want to validate if a private member is null or empty (which is exposed by its property). It would be better to declare inside the class of the object to encapsulate the behavior instead of doing the validation at every moment where is used, but the question is if better to do it as a property or method?
public bool HasValue()
{
return String.IsNullOrEmpty(this.privateMember) == false;
}
or
public bool HasValue
{
get
{
return String.IsNullOrEmpty(this.privateMember) == false;
}
}
Example of usage:
if(myObject.HasValue()){
}
or
if(myObject.HasValue){
}
What is better? Any impact or it just visual?
Well that certainly feels more like a property to me than a method - and it's certainly in-keeping with things like Nullable<T>.HasValue
.
Other differences to consider:
There shouldn't be any performance impact.
As an aside, rather than comparing against false
, I'd write the implementation as:
return !string.IsNullOrEmpty(privateMember);
See more on this question at Stackoverflow