简体   繁体   中英

How to display Yes/No instead of True/False for bool? in c#

I get the error "Cannot implicitly convert type 'string' to 'bool'. How do I return 'Yes' or 'No' instead of true/false?

public bool? BuyerSampleSent
{
    get { bool result;
          Boolean.TryParse(this.repository.BuyerSampleSent.ToString(), out result);
        return result ? "Yes" : "No";
    }
    set { this.repository.BuyerSampleSent = value; }
}

You can't return a string if the return type is bool (or bool? in this case). You return a bool :

return result;

Notice, however, that you ask...

How to display Yes/No...

This code isn't displaying anything. This is a property on an object, not a UI component. In the UI you can display whatever you like using this property as a flag:

someObject.BuyerSampleSent ? "Yes" : "No"

Conversely, if you want a display-friendly message on the object itself (perhaps it's a view model?) then you can add a property for that message:

public string BuyerSampleSentMessage
{
    get { return this.BuyerSampleSent ? "Yes" : "No"; }
}

Your method returns a bool as @Pierre-Luc points out. You need to change that to a String.

You cannot return a bool value "Yes" or "No". In C#, bool is a keyword for Boolean Data Type.You cannot override this behavior of a keyword.
Read more about C# Boolean Data Type here .

In your case you can do the following:

public string BuyerSampleSent
{
    get
    {
        string result= "No";
        if (this.repository.BuyerSampleSent.Equals("true",StringComparisson.OrdinalIgnoreCase)) // <-- Performance here
            result = "Yes";
        return result;
    }
    set
    {
        this.repository.BuyerSampleSent = value;
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM