Jéf Bueno
Jéf Bueno

Reputation: 434

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#?

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

Upvotes: 1

Views: 1539

Answers (3)

Alexander Maxwell
Alexander Maxwell

Reputation: 17

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

Upvotes: 1

Nikolay Kostov
Nikolay Kostov

Reputation: 16963

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.

Upvotes: 5

Jon Skeet
Jon Skeet

Reputation: 1500615

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, e.g.

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.

Upvotes: 6

Related Questions