I'm specifically calling attention to null-propagation as it pertains to bool?
and the use of a bool
returning method. For example, consider the following:
public static bool IsAttributedWith<TAttribute>(this JsonProperty property)
where TAttribute : Attribute
{
return property?.AttributeProvider
.GetAttributes(typeof(TAttribute), false)
.Any();
}
This doesn't compile, and the following error exists:
Cannot implicitly convert bool? to bool. An explicit conversion exists (are you missing a cast)?
This implies that it is treating the entire body of the method as a bool?
, as such I would assume that I could say .GetValueOrDefault()
after the .Any()
but this is not allowed as .Any()
returns bool
not bool?
.
I know that I could do either of the following as a work around:
public static bool IsAttributedWith<TAttribute>(this JsonProperty property)
where TAttribute : Attribute
{
return property?.AttributeProvider
.GetAttributes(typeof(TAttribute), false)
.Any()
?? false;
}
Or
public static bool IsAttributedWith<TAttribute>(this JsonProperty property)
where TAttribute : Attribute
{
var any =
property?.AttributeProvider
.GetAttributes(typeof(TAttribute), false)
.Any();
return any.GetValueOrDefault();
}
Or
public static bool IsAttributedWith<TAttribute>(this JsonProperty property)
where TAttribute : Attribute
{
return property?.AttributeProvider
.GetAttributes(typeof(TAttribute), false)
.Any()
?? false;
}
My question is, why can I not directly invoke .GetValueOrDefault()
chaining on the .Any()
invocation?
public static bool IsAttributedWith<TAttribute>(this JsonProperty property)
where TAttribute : Attribute
{
return (property?.AttributeProvider
.GetAttributes(typeof(TAttribute), false)
.Any())
.GetValueOrDefault();
}
I think this would make sense as the value is actually bool?
at this point and not bool
.