C# if (strValue == "FALSE" | strValue == "TRUE") - c#

I have a string that contains a value of either TRUE or FALSE or null, this value is read from a text file which is outside of my control. What is the best way to use '|' with 'if'? Keeping in mind strValue could also be null, if strValue is null then I don't want to enter the if statement.
if (strValue == "FALSE" | strValue == "TRUE")
{
//do stuff
}
Thanks

if (strValue == "FALSE" || strValue == "TRUE") {
// ...
}
to benefit from short circuiting. The second expression will not be tried if the first evaluates to true.
If you need case-insensitive comparisons:
if ("FALSE".Equals(strValue, StringComparison.InvariantCultureIgnoreCase) ||
"TRUE".Equals(strValue, StringComparison.InvariantCultureIgnoreCase)) {
// ...
}
Note that calling .ToUpper() or .ToLower() on null will throw NullReferenceException.

From your question, it sounds like all you REALLY care about is that the string is NOT NULL. You then have two options:
if (!string.IsNullOrEmpty(strValue))
{
//Do stuff with "TRUE" or "FALSE"
}
or, if you know it will NEVER be an empty string (""):
if (strValue != null)
{
//Do stuff with "TRUE" or "FALSE"
}
I would recommend the first choice.

I would seriously consider using ToUpper if it's out of your control - you never know when someone changes it to "True" or "true".
if (strValue.ToUpper() == "FALSE" || strValue.ToUpper() == "TRUE") {
}
Regarding the responses about ToUpper and unnecessary defensive programming:
The original question said "read from a text file which is outside of my control", and "TRUE or FALSE or null". As far as I know there is no universal way of indicating NULL in text files. In CSV files, you could treat ,, as NULL or "" (empty string). In fixed width text files, you could treat all spaces as NULL, "" or "<some spaces>", for example.
So the OP has already done some data conversion/interpretation to get to this point.

Or perhaps:
if (strValue == "FALSE") {
// do stuff
} else if (strValue == "TRUE") {
// do other stuff
} else {
// strValue was NULL or invalid.
}
Depending on your needs.

You can put all of them into a single if statement:
if (!string.IsNullOrEmpty(strValue) && (strValue == "TRUE" || strValue == "FALSE")
{
//do stuff
}
The first condition will be evaluated first, and then the others afterwards. I prefer to have the explicit null check, to help other probably less experienced developer to understand the code.

if strValue is null then I don't want to enter the if statement
If that really is the case then why are you worried about the "|" (bitwise or) operator.
You could just write:
if (strValue != "NULL")
{
}
What you probably mean is to use the (logical or) operator "||" on the true or false values.
if (strValue == "TRUE" || strValue == "FALSE")
{
}
I could keep guessing on the scenarios but I'm sure you get the gist of it.

Since there are only three options "TRUE", "FALSE", "null", I recommend using the following:
if(String.Compare(strValue, "null") != 0){
//do stuff
}
If you need a maximum compatibility and cannot rely on your input, you could switch strValue with strValue.toLower().

Related

Where and how to use && Operators

I have this piece of code which i simplified from my app. It does what I want but I know its not put in the most efficient way because I'm still having some trouble understanding the && and & operators.
if (AgeInput.Text.Equals(""))
{
Textblock1.Text = "✘";
}
else if (AgeInput.Text.All(Char.IsNumber)){
Textblock1.Text = "✔";
//DO-THIS-A
}
else
{
Textblock1.Text = "✘";
}
I need it to make sure there is no white spaces in the string and to also check so its not empty and finally check if its a number, If it ticks all those requirements it will //DO-THIS-A
Whats the most efficient way to do this?
EDIT:
If somebody knows how to make a XAML textbox numerical only (so no whitespaces) that would be even better (only a single property or don't worry otherwise)
if(!String.IsNullOrEmpty(AgeInput.Text) && AgeInput.Text.All(char.IsNumber))
Textblock1.Text = "✔";
else
Textblock1.Text = "✘";
String.IsNullOrEmpty returns true if the input is as stated: Null or Empty.
We Invert that with the "!", so that it returns true if it isn't empty.
Then we add the && Operator to expand the if condition and ask if the text only contains numbers.
Also look here: For a description of the difference between &, && and |, ||
Not really sure I understand your question, because && and & are for totally different uses.
if (string.IsNullOrWhiteSpace(AgeInput.Text))
{
Textblock1.Text = "✘";
}
else if(Char.IsNumber(AgeInput.Text.All))
{
Textblock1.Text = "✔";
}
The & is a binary operator and && is a logical operator.

How to write shorthand if-statement with multiple conditions

For example i want to write:
txt1.Text=="A" || txt2.Text="A" ? return true : return false
I know how to work with one condition but with two i don't know.
The txt2.Text="A" instead of txt2.Text=="A" it's not what i meant.
My question was how do i add a condition to this specific if.
Yes, i know how to use in if.
the regular way to use in the other if is:
txt1.Text=="A"? return true: return false
and i want to improve that.
The code that i have written doesn't work.
Thank you
Are you looking for
return txt1.Text == "A" || txt2.Text == "A";
?
I think this is what you are looking for.
if(txt1.Text == "A" || txt2.Text == "A") //checks if txt1 is A OR txt2 is A
{
return true;
}
else
{
return false;
}

Is there a better way to check for boolean logic

I have an xml filelike so
<Config>
<Allowed></Allowed>
</Config>
The Allowed tag is read like this:
string isAllowed = (string)xml.Root
.Element("Config")
.Elements("Allowed")
.SingleOrDefault();
isAllowed is supposed to take a default value of true when
The tag is not present
Is present but is empty
Has any other value other than true, false, yes, or no.
Here is the code which does this:
if (isAllowed == null)
{
DoSomething();
return true;
}
if (isAllowed.Length == 0)
{
DoSomething();
return true;
}
if (isAllowed.Length != 0)
{
if (isAllowed.ToUpper() != "FALSE" && isAllowed.ToUpper() != "NO")
{
DoSomething();
return true;
}
}
There's got to be a better way to do this?
if (isAllowed == null)
{
DoSomething();
return true;
}
if (isAllowed.Length == 0)
{
DoSomething();
return true;
}
Can be replaced with:
if (string.IsNullOrEmpty(isAllowed)
{
DoSomething();
Return true;
}
But actually, given your criteria I think string.IsNullOrWhiteSpace(isAllowed) would be more appropriate as it will return true if the tag's contents are "empty".
Also, you don't need the following condition a second time, because if if the condition was met the first time around the function will return (short circuit evaluation). This means that the statements you currently have in the second If block would never be executed anyway.
if (isAllowed.Length != 0)
My first instinct to make this cleaner was to take the same approach as Jon did in his answer, there's no advantage in repeating it. However, I did consider this as another good design as should you introduce more conditions it will be much cleaner:
private static bool Validate(string isAllowed)
{
var defaultTrueConditions = new[] {"true", "false", "yes", "no"};
if (string.IsNullOrWhiteSpace(isAllowed) ||
defaultTrueConditions.Contains(isAllowed, StringComparer.OrdinalIgnoreCase))
{
DoSomething();
return true;
}
return false;
}
It sounds like you might be better off like this:
// This deals with the nullity aspect. (The "Yes" is just for clarity - it could
// be any value other than "No" or "False" in some form.)
isAllowed = isAllowed ?? "Yes";
bool isFalse = isAllowed.Equals("No", StringComparison.OrdinalIgnoreCase) ||
isAllowed.Equals("False", StringComparison.OrdinalIgnoreCase);
return !isFalse;
Basically the fact that you're defaulting to true means that the return value should only be false if you find an element and it's got a value of No or False, in a case-insensitive way. Note that I've used an ordinal match here - you may want to change that, e.g. to CurrentCultureIgnoreCase or InvariantCultureIgnoreCase.
It's not clear where the DoSomething method call comes in, but I would separate that out anyway. Write one method which just determines the appropriate value, as shown above - and then have:
bool allowed = CheckAllowed(doc);
if (allowed)
{
DoSomething();
}
// And use allowed here too
That's a much cleaner separation to my mind.

Tricky if statement

Is it possible to convert this if statement into a one line statement ?
if (value != DBNull.Value)
{
dic.Add(columnName);
}
else if (!skipNullValues)
{
dic.Add(columnName);
}
if (value != DBNull.Value || !skipNullValues) dic.Add(columnName);
Use a logical OR:
if (value != DBNull.Value || !skipNullValues)
dic.Add(columnName);
I would keep the addition on a new line for clarity, although for a simple statement like this you're probably alright to drop the curly brackets. You do need to be careful if you try to add more logic in the future though obviously in the branch of the if.
if (!(value == DBNull.Value && skipNullValues))
dic.Add(columnName);
If you edit to include why making it a single line will help you might get a more suitable answer. Here are a few different approaches you could take..
First off, in a single line as you requested:
if ((value != DBNull.Value) || (value == DBNull.Value && !skipNullValues)) { dic.Add(columnName); }
Alternatively you might want to look into using ternary operators if you need something more compact.
var result = (istrue) ? (return valIfTrue) : (return valIfFalse);
More info on ternary operators:
http://msdn.microsoft.com/en-us/library/ty67wk28%28v=vs.80%29.aspx
Most likely (depending on your situation) you should consider creating a method similar to this:
public void AddColumnToDic(object value, string columnName)
bool skipNullValues = false; // todo: read from configuration
if ((value != DBNull.Value) || (value == DBNull.Value && !skipNullValues))
{
dic.Add(columnName);
}
}
and simply call it for every cell value you encounter.

Compare strings in if statement

Trying to write a piece of code to compare two strings. If either are equal to the textbox then it opens a new winform. I know how to do the winform part.
string CreditCard1 = "Some numbers";
string CreditCard2 = "Some Numbers";
string RFIDCard1 = "E00700000330E44C";
string RFIDCard2 = "E00700000338E539";
if(CardScan_txtBx = CreditCard1 || RFIDCard1)`
I get an error from MSVS 2010 saying:
Operator '||' cannot be applied to operands of type 'string' and 'string'
Is there a way to do what I want?
This line is the culprit:
if(CardScan_txtBx = CreditCard1 || RFIDCard1)`
Try:
if(CardScan_txtBx.Text == CreditCard1 || CardScan_txtBx.Text == RFIDCard1)
On a side note, it scares me that you're apparently working with credit card information, but don't know how to compare values in a text box. I really, really hope, for the sake of your customers, that you plan on investigating how to securely manage that information.
There are three problems here:
You cannot compare against multiple values using an OR (||). This is a surprisingly common misconception, but makes no sense to the compiler.
Comparison in C# is done with ==. = is for assignment.
A TextBox is not a string; you need to use its Text property to get or set the text it contains.
So in the end, your if statement should look like this:
if(CardScan_txtBx.Text == CreditCard1 || CardScan_txtBx.Text == RFIDCard1) {
// ...
}
Ok you have 2 issues here, firstly single equals is assignment not comparison and secondly each argument separated by an or needs to be a bool, ie should be
if(CardScan_txtBx == CreditCard1 ||CardScan_txtBx == RFIDCard1)
Could you use else if?
if(CardScan_txtBx == CreditCard1)
{
//Do something
} else if(CardScan_txtBx == RFIDCard1)
{
//Do something
}
The other answers have the correct code, here is an explanation of the why. When you use the || operator, it is expecting an expression on either side to be something that evaluates to a bool (true or false). When you wrote CardScan_txtBx.Text == CreditCard1 || RFIDCard1 you have an statement that evaluates to a bool on the left, CardScan_txtBx.Text == CreditCard1 and you have a statement that evaluates to string on right RFIDCard1 Because a string is not a bool, you get the compile time error. that is why you must repeat the == operator on the right hand side so that you say CardScan_txtBx.Text == RFIDCard1
Try out with following code.....
if (CardScan_txtBx.Equals(CreditCard1) || CardScan_txtBx.Equals(RFIDCard1))
{
//Code
}
Try this:
if (CardScan_txtBx.Text == CreditCard1 || CardScan_txtBx.Text == RFIDCard1)
See here: http://msdn.microsoft.com/en-us/library/53k8ybth%28v=vs.71%29.aspx
Not: =
Right: expr1 == expr2
You can also use a List.
List<string> listOfValidStrings = new List<string>();
//Initialise all valid strings.
if(listOfValidStrings.contains(txtbox.text())
{ do something.}

Categories

Resources