Compare strings in if statement - c#

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.}

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.

Validating a Radio Box

I'm simply trying to check that one of the three radio boxes has been checked, for some reason even when in debug console all boxes '.Selected = false' it is still skipping over my error message. Any help is appreciated.
if ((rdoIndoor.Checked = false ) && ( rdoOut.Checked = false ) && ( rdoSwimming.Checked = false ))
{
MessageBox.Show("Please select an event style");
}
You are using an assignment operator instead of a comparison operator. The = operator is for assignment. Use == for comparison.
Better yet, get rid of your == operator altogether, and use the ! operator, like this:
if ( !rdoIndoor.Checked && !rdoOut.Checked && !rdoSwimming.Checked )
{
MessageBox.Show( "Please select an event style" );
}
The equality operator, used to compare values, is ==
So your code should be:
if ((rdoIndoor.Checked == false ) &&
( rdoOut.Checked == false ) &&
( rdoSwimming.Checked == false ))
......
use double equals signs (rdoIndoor.Checked **==** false) etc
Single '=' means assignment, i. e. from now let 'rdoIndoor.Checked' be false.
Double '==' is logical test.
You probably know that ;)

How to use AND operator logic in Or Operator i cant solve it in interview?

suppose i have a code like this,
(var1==true && var2==true)
{
somemethod();
}
suppose we have a language in which we do not have && operator it is not exsis in the language then what changing in the condition to make it like (var1==true || var2==true)
and work like and operator that when both condion true then it enter in the loop and do not use any code like using if condition for both condition to make it work
hopes for your suggestions thanks in advance
if (!(!var1 || !var2))
{
somemethod();
}
By DeMorgan's law:
a and b === !!(a and b) === !(!a or !b)
http://en.wikipedia.org/wiki/De_Morgans_laws
You can simply use the below:
(!(!var1 || !var2))
Steps below:
(var1==true && var2==true)
(var1 && var2)
!(!(var1 && var2))
!(!var1 || !var2)
Since they are booleans, you could also use '&'
if (var1 & var2) {
}
which 'could' be simpler for humans to understand, then multiple negations.
if (var1)
if (var2)
someMethod(); // var1 and var2 are both true

Concat string in IsNullOrEmpty parameter

I was looking at a piece of code I wrote in C#:
if(string.IsNullOrEmpty(param1) && string.IsNullOrEmpty(param2) && string.IsNullOrEmpty(param3))
{
// do stuff
}
and decided to make it more readable/concise
if(string.IsNullOrEmpty(param1+param2+param3))
{
// do stuff
}
But looking at it I can't help but cringe. What are your thoughts on this? Have you ever done something like this and do you use it whenever applicable.
Note: The code previous to this line would manipulate a collection by adding specific items depending on if the a param (param1,param2,param3) is NOT empty. This if statement is meant for validation/error handeling.
Personally I prefer the former over the latter. To me the intent is more explicit -- checking if all parameters are null/empty.
The second also hides the fact it does handle nulls. Null strings are odd. Jason Williams above, for example, didn't relise that it does in fact work.
Maybe write it something like this, which is a bit more readable:
bool paramsAreInvalid =
string.IsNullOrEmpty(param1)
&& string.IsNullOrEmpty(param2)
&& string.IsNullOrEmpty(param3);
if (paramsAreInvalid)
{
// do stuff
}
It's a small thing, but I think a minor reformatting of your original results in improved readability and makes the intent of the code about as crystal clear as can be:
if ( string.IsNullOrEmpty(param1) &&
string.IsNullOrEmpty(param2) &&
string.IsNullOrEmpty(param3) )
{
// do stuff
}
Consider this similar set of examples:
if ( c == 's' || c == 'o' || c == 'm' || c == 'e' || c == 't' || c == 'h' || c == 'i' || c == 'n' || c == 'g') {
// ...
}
if ( c == 's' ||
c == 'o' ||
c == 'm' ||
c == 'e' ||
c == 't' ||
c == 'h' ||
c == 'i' ||
c == 'n' ||
c == 'g') {
// ...
}
That won't work. If any of the strings are null, you'll get a null dereference exception. You need to check them before you use them.
In addition, it's very inefficient. You are concatenating all the strings into a new string, then test if this is non-empty. This results in one or more memory allocations and potentially a lot of data being copied, only to be immediately thrown away and garbage collected a moment later.
A better approach is to write a method that takes variable arguments or a list of strings and checks them one by one using IsNullOrEmpty in a loop. This will be more efficient, safe, but still achieve the desired result of tidy code in your if statement.
If you can get the params in a collection (which if it's function you can with the params keyword) then this might work:
if (myParams.Any(IsNullOrTrimEmpty)
{
// do stuff
}
The example uses this string extension and myParams is a string[].
The original code, though longer, is more clear in its intent, and likely similar performance-wise. I'd leave it alone.

What does this snippet of C# code do?

What does result.IsVisible equal?
if(a==b)
result.IsVisible = obj1.status.abc_REPORT == 'Y'
&& obj1.AnotherValue.ToBoolean() == false;
That depends on the values of obj1.status.abc_Report and obj1.AnotherValue.ToBoolean() (and it all depends on whether a==b or not).
I'm not quite sure of what the real question is here - which bit is confusing you?
One bit which may be confusing you is the shortcircuiting && operator (and possibly the lack of bracing!)
The && operator will only evaluate its right hand side if the left hand side evaluates to true: and the overall result of the expression is true if and only if both sides evaluates to true. (I'm assuming no strange user-defined conversions here.)
So another way of writing it would be:
if (a == b)
{
bool visibility = false;
if (obj1.status.abc_REPORT == 'Y')
{
if (obj1.AnotherValue.ToBoolean() == false)
{
visibility = true;
}
}
result.IsVisible = visibility;
}
Note that a condition comparing Booleans, like this:
obj1.AnotherValue.ToBoolean() == false
would usually be written like this:
!obj1.AnotherValue.ToBoolean()
(Note the exclamation mark at the start - the logical "not" operator.)
The same as this, in many less lines:
if (a==b) {
if (obj1.status.abc_REPORT == 'Y') {
if (obj1.AnotherValue.ToBoolean() == false) {
result.IsVisible = true;
}
else {
result.IsVisible = false;
}
}
else {
result.IsVisible = false;
}
}
In simple words:
If a is equal to b:
result will be visible only if:
object1's status's abc_report is Yes(Y = Yes most probably) AND object1's other value cannot be converted to a Boolean
I'm guess result.IsVisible is a boolean
It will be true if the following conditions are true:
obj1.status.abc_REPORT == 'Y'
and
obj1.AnotherValue.ToBoolean() == false
Also, a == b must be true to enter the initial if
lets go line by line:
if(a==b)
obvious if value of a equals value of b the execute following line
result.IsVisible = obj1.status.abc_REPORT == 'Y'
&& obj1.AnotherValue.ToBoolean() == false;
result is some object (maybe winforms controls etc) which has a property IsVisible set it to true if obj1.status.abc_REPORT is equal to 'Y' and also obj1.AnotherValue.ToBoolean() is equal to false;

Categories

Resources