Extension method that accepts Expression<Func<T>> expression as parameter
No need for Expression
at all, just use Func<WillAnswer, TProp>
:
public static TProp GetNullIfNotSet<TProp>(this WillAnswer answer, Func<WillAnswer, TProp> func)
{
if (answer.Id == 0) return default(TProp);
return func(answer);
}
Please note, that this will not always return null
but the default value (in case the property is a value-type).
Update (as per your request):
In order to be able to return null
for all passed properties, the method signature was changed to return object
instead:
public static object GetNullIfNotSet<TProp>(this WillAnswer answer, Func<WillAnswer, TProp> func)
{
if (answer.Id == 0) return null;
return func(answer);
}
But, you'll lose the benefits of generics and you'll end up with explicit casts to Nullable<T>
:
var emptyIfNewObject = (bool?)answer.GetNullIfNotSet(o => o.HasBusinessAssets)
Which is less ideal.
It seems that you need a Func<WillAnswer, T>
not an expression:
public static T GetDefaultIfNotSet<T>(this WillAnswer answer, Func<WillAnswer, T> func) {
if (null == answer)
throw new ArgumentNullException("answer");
else if (null == func)
throw new ArgumentNullException("func");
return answer.Id == 0 ? return default(T) : func(answer);
}
EDIT: if you want to ensure null
you can restrict generic T
:
public static T GetNullIfNotSet<T>(this WillAnswer answer, Func<WillAnswer, T> func)
where T: class { // no structs here
if (null == answer)
throw new ArgumentNullException("answer");
else if (null == func)
throw new ArgumentNullException("func");
return answer.Id == 0 ? return null : func(answer);
}