I have different properties that can provide a value and I would like to return the first one that satisfies a specified condition.
The problem is when one of the sources is a class
and is null
, I do get a nice Object reference not set to an instance of an object..
I can't find a property to check against the nullity of the current provider, whether on the Func<T,bool>
or the Expression<Func<Media,T>>
.
Do you know how can I check against the nullity of a function target ?
public int TempoInteger
{
get
{
double result;
// In this case, AudioSummary is a class that can be null
if (TryGetValue(out result, s => s > 0.0d, s => s.TempoBass, s => s.AudioSummary.Tempo))
{
return (int)Math.Round(result);
}
return -1;
}
}
private AudioSummary AudioSummary {get; set;}
/// <summary>
/// Tries to get a value from multiple expressions, first expression value that satisfies the predicate will be returned. If no value satisifes the predicate the default value of <typeparamref name="T"/> will be returned.
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="result"></param>
/// <param name="predicate"></param>
/// <param name="expressions"></param>
/// <returns></returns>
private bool TryGetValue<T>(out T result, Func<T, bool> predicate, params Expression<Func<Media, T>>[] expressions)
{
foreach (var expression in expressions)
{
Func<Media, T> func = expression.Compile();
// 'System.NullReferenceException' occurs here when AudioSummary is null
T t = func(this);
var b = predicate(t);
if (b)
{
result = t;
return true;
}
}
result = default(T);
return false;
}
public sealed class AudioSummary
{
[JsonProperty("tempo")]
public double Tempo { get; set; }
// ...
}