简体   繁体   中英

Can I implement an implicit 'conversion' from string to boolean in C#?

There's any way to implement an implicit conversion from string to bool using C#?

Eg I have the string str with value Y and when I try convert (cast) to boolean it must return true .

No. You can't create user-defined conversions which don't convert either to or from the type they're declared in.

The closest you could easily come would be an extension method, eg

public static bool ToBoolean(this string text)
{
    return text == "Y"; // Or whatever
}

You could then use:

bool result = text.ToBoolean();

But you can't make this an implicit conversion - and even if you could , I'd advise you not to for the sake of readability.

Here is an extension method that you can use for any string.

public static bool ToBoolean(this string input)
{
    var stringTrueValues = new[] { "true", "ok", "yes", "1", "y" };
    return stringTrueValues.Contains(input.ToLower());
}

Here is an example of using this extension method:

Console.WriteLine("y".ToBoolean());

The result will be True .

You'll need to make the method on you own. There is no way to just cast a string to a bool. You'll end up with true if the string is not null, I believe. Just make a Boolean method that returns true if the string it's passed is y or false otherwise

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