Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I return null or bool from a function

Tags:

c#

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?

like image 270
Alan2 Avatar asked Jul 08 '17 13:07

Alan2


People also ask

How do you return a null from a function?

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).

How do I return a null function in SQL?

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.

Can any function return null?

Yes - a function can return a null 'instance'. It does NOT return a null value.

Can a bool function return null?

Null should not be returned from a "Boolean" method.


1 Answers

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.

like image 140
Salah Akbari Avatar answered Sep 23 '22 10:09

Salah Akbari