Jasmine
Jasmine

Reputation: 5326

I have a method that returns string however the variable is of type nullable boolean

I get a build error in the following:

protected override string SHow()
{
    return _type ? "Y" : "N";
}

_type is of type nullable bool. I get that "cannot convert from ?bool to bool.

Could you please help resolve?

Upvotes: 2

Views: 110

Answers (3)

Mukesh Adhvaryu
Mukesh Adhvaryu

Reputation: 646

If bool? has value then It is indeed true or false. Besides nullable.HasValue is required when we want to access value not when we compare value. So the following will also work:

protected override string SHow()
{ 
    string result = null;
    if(_type==true)
        result = "Y"; // has value & value is true
    else if (_type==false)
        result="N"; // has value & value is false
    return result; // retuing null if no value
}

Statement "_type==true" will never fail or give you a compile error because compiler not only check for null, it also check for true or false and return true only if _type is NOT Null and also has value true. Equality comparison for any primitive type nullable behaves the same way so nullable.HasValue check is not necessary when you compare.

Upvotes: 0

glenebob
glenebob

Reputation: 1983

A nullable type provides access to its underlying value with the Value property.

return _type.HasValue && _type.Value ? "Y" : "N";

OK, editing to return null...

const string trueValue = "True";
const string falseValue = "False";

return _type.HasValue ? (_type.Value ? trueValue : falseValue) : null;

Upvotes: 3

mohsen
mohsen

Reputation: 1806

Use

protected override string SHow() 
{
    if(_type ==null)
    {
        return "";
    }
     return _type.Value ? "Y" : "N";
 }

Upvotes: 0

Related Questions