Nano HE
Nano HE

Reputation: 9307

Bool Variable and string value compare in C#

If I declared a bool isTrue = false; // init it to false

and I can get the value from a string strVal = T; // I assumed it is the TRUE value

I heard it is not a good code style to compare string in C# like

if (isTrue.tostring() == strVal) {}.

Some time, I covert the the string variable to enum then I can compare it more convenient.

Is there any good method to do it?

Upvotes: 1

Views: 19910

Answers (8)

Tasnim Fabiha
Tasnim Fabiha

Reputation: 1238

How about trying this simple way to determine the value of bool variable isTrue:

isTrue = strVal == "T";

isTrue will return true if the strVal is equaled to "T". And return false if not.

Upvotes: 0

Matt Mitchell
Matt Mitchell

Reputation: 41823

Yes, you parse the string into a boolean first.

Try this:

bool someBool = false; 

string boolVal = "true";
bool stringBool;
bool.TryParse(boolVal, out stringBool);

if (someBool == boolVal) 
{

}

Alternatively to handle 'T' and 'F' try these methods:

public bool ParseString(string maybeBool)
{
    return ParseString(maybeBool, false);
}

public bool ParseString(string maybeBool, bool def)
{
    bool stringBool;
    if (bool.TryParse(maybeBool, out stringBool))
        return stringBool;

    if (string.Equals(maybeBool, "T", StringComparison.OrdinalIgnoreCase))
        return true;

    if (string.Equals(maybeBool, "F", StringComparison.OrdinalIgnoreCase))
        return false;

    return def;
}

Upvotes: 7

HerrVoennchen
HerrVoennchen

Reputation: 351

Yet another version which i use a lot is simply Convert.ToBoolean(stringFromBoolVal)

regards

Upvotes: 1

MrFox
MrFox

Reputation: 5116

If you really want to do string comparisons:

if (string.Equals(isTrue.ToString(), strValue)) { }

Upvotes: 0

Arseny
Arseny

Reputation: 7351

you may compare boolean type instead.

bool temp = bool.Parse(strVal);

if(isTrue == temp)

Upvotes: 1

Oded
Oded

Reputation: 499002

There is no need to convert boolean values to strings in order to compare the two. You can simply compare the two boolean values directly:

if (isTrue == boolVal) {}

Update: (following updated question)

You can parse a string into a boolean and use the resulting boolean in your comparison (as above), using either bool.Parse or bool.TryParse.

Upvotes: 1

Kimi
Kimi

Reputation: 14099

bool.Parse(boolVal) == isTrue 

Upvotes: 1

sashaeve
sashaeve

Reputation: 9617

Try bool.Parse() method instead.

Upvotes: 3

Related Questions