How to define a private member behavior, as a method or property? C#

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?

Jon Skeet
people
quotationmark

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:

  • You can generally bind against properties but not methods; not sure you'd want to bind against this anyway
  • You can't use properties for method group conversions (unfortunately) to create delegates
  • Properties are automatically evaluated when debugging; methods aren't

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);

people

See more on this question at Stackoverflow