I have a class that I use to display on a web page fieldset. However, all of the properties of this class are optionally filled in by the user, which means all of them could be null/default. In this case I would like not to render the fieldset at all, instead of displaying an empty one.
I wrote a simple isEmpty()
method that checks all property values using reflection, but I'm afraid this may become way too expansive.
public class User
{
[Display(Name = "First Name:")]
public string FirstName { get; set; }
[Display(Name = "Last Name:")]
public string LastName { get; set; }
public bool isEmpty()
{
Type t = this.GetType();
var properties = t.GetProperties(BindingFlags.Public | BindingFlags.Instance);
foreach (var prop in properties)
{
var value = prop.GetValue(this, null);
if (value != null && (string)value != "")
{
return false;
}
}
return true;
}
}
The isEmpty()
, of course, assumes all properties are strings.
What do you think? Will this become potentially expansive as the class grows?
IsEmpty
instead ofisEmpty
. This is per Microsoft's Capitalization Guideline. \$\endgroup\$