There's several workaround for what you're trying to achieve.
Wrap the expression invocation inside a try-catch block
private bool TryGetValue<T>( out T result, Func<T, bool> predicate, params Expression<Func<Media, T>>[] expressions) { ... T t; try { t = func(this); } catch (NullReferenceException) { t = default(T); } ... }
Validate the expression for
Null
before passing it toTryGetValue()
public int TempoInteger { get { double result; if (TryGetValue(out result, s => s > 0.0d, s => s.TempoBass, s => s.AudioSummary != null ? s.AudioSummary.Tempo : 0.0d)) { return (int)Math.Round(result); } return -1; } }
Use the
IfNotNull
extension method, which does the same thing as point#2
but fancierpublic static class IfNotNullExtensionMethod { public static T2 IfNotNull<T1, T2>(this T1 t, Func<T1, T2> fn) where T1: class { return t != null ? fn(t) : default(T2); } } ... public int TempoInteger { get { double result; if (TryGetValue(out result, s => s > 0.0d, s => s.TempoBass, s => s.AudioSummary.IfNotNull(x => x.Tempo))) { return (int)Math.Round(result); } return -1; } } ...
Credits for the
IfNotNull
extension methods goes to: here, here, and hereUse the
Maybe
extensions method: maybe.codeplex.com. (disclaimer: I haven't tested this one, but it's mentioned in point#3
credits links)