Reputation:
I am trying to figure out how to call a class method on a property of that class. Here are my two classes:
public class MrBase
{
public int? Id { get; set; }
public String Description { get; set; }
public int? DisplayOrder { get; set; }
public String NullIfEmpty()
{
if (this.ToString().Trim().Equals(String.Empty))
return null;
return this.ToString().Trim();
}
}
public class MrResult : MrBase
{
public String Owner { get; set; }
public String Status { get; set; }
public MrResult() {}
}
MrResult inherits from MrBase.
Now, I want to be able to call the NullIfEmpty method on any of the properties of these classes... like so:
MrResult r = new MrResult();
r.Description = "";
r.Description.NullIfEmpty();
r.Owner = "Eric";
r.Owner.NullIfEmpty();
Thanks.
Eric
Upvotes: 1
Views: 282
Reputation: 82096
If you want this code to be specific to your model, then you could built it into your setters with a slight modification to your NullIfEmpty
method e.g.
private String _owner;
public String Owner
{
get { return _owner; }
set { _owner = NullIfEmpty(value); }
}
...
public String NullIfEmpty(string str)
{
return str == String.Empty ? null : str;
}
Upvotes: 3
Reputation: 48965
You should write an extension method for string
:
public static class StringExtensions
{
public static string NullIfEmpty(this string theString)
{
if (string.IsNullOrEmpty(theString))
{
return null;
}
return theString;
}
}
Usage:
string modifiedString = r.Description.NullIfEmpty();
If your main goal is to automatically "modify" each string
property of your classes, you can achieve this using reflection. Here's a basic example:
private static void Main(string[] args)
{
MrResult r = new MrResult
{
Owner = string.Empty,
Description = string.Empty
};
foreach (var property in r.GetType().GetProperties())
{
if (property.PropertyType == typeof(string) && property.CanWrite)
{
string propertyValueAsString = (string)property.GetValue(r, null);
property.SetValue(r, propertyValueAsString.NullIfEmpty(), null);
}
}
Console.ReadKey();
}
Upvotes: 2