I have this function:
public bool GetBoolSetting(Settings setting)
{
return int.Parse(GetStringSetting(setting)) == 0 ? false : true;
}
There is a problem in that GetStringSetting(setting)
can return null
, "0"
or "1"
. When it returns a null
I get an exception.
Is it possible for me to make the GetBoolSetting
function return a null if this happens?
Use Nullable Reference Types If the developer really needs to return a null value from the method (in 99% of cases this is not necessary), the return type can be marked as a nullable reference type (the feature was introduced in C# 8.0).
COALESCE() In SQL, the COALESCE function returns the first non-NULL expression in the list of inputs. The COALESCE function will return null if all of the expressions evaluate to null.
Yes - a function can return a null 'instance'. It does NOT return a null value.
Null should not be returned from a "Boolean" method.
You can change the type of your method to Nullable<bool>
and continue to your one linear statement like below:
public bool? GetBoolSetting(Settings setting)
{
return GetStringSetting(setting) != null ?
int.Parse(GetStringSetting(setting)) != 0 : new bool?();//Or default(bool?)
}
You can also use default(bool?)
instead of new bool?()
which returns the default value of Nullable bool that is null.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With