You can do something like that:
public static TProperty TryGetValue<T, TProperty>(
this T source,
Func<T, TProperty> getter,
TProperty defaultValue = default(TProperty))
{
if (source == null)
return defaultValue;
return getter(source);
}
Use it like that:
db.Scanners.FirstOrDefault(s => s.ScannerID == 24)
.TryGetValue(s => s.FriendlyName, "N/A");
This approach is much faster than using reflection, and also safer, because an invalid property name would be detected at compile time. It is also strongly typed, which means you don't need to cast the result.
Another approach that doesn't require a new extension method is to project the sequence before calling FirstOrDefault
:
db.Scanners.Select(s => s.FriendlyName)
.FirstOrDefault() ?? "N/A";