Compare two values in if [duplicate] - c#

This question already has answers here:
Comparing a variable to multiple values [duplicate]
(7 answers)
Closed 9 years ago.
Let's say I have an if that goes like this:
if(condition1 != asd && menu != menu1 && menu != menu2)
Can this be shortened to something like:
if(condition1 != asd && menu != (menu1 && menu2))
I tried putting parentheses around the second condition either around the two that it should not be, and around the whole thing but it does not pass the compiler.
Is it possible to shorten the second condition this way? Or is there a better way to do it?
PS. I had no idea what to call this, so feel free to edit the title.

Imagine if you were comparing numbers:
if (myNumber != 5 && myNumber != 10)
You could add the numbers being compared to a list first, then use a .Contains():
var forbiddenNumbers = new List<int> { 5, 10 };
if (!forbiddenNumbers.Contains(myNumber))
I don't see any reason you couldn't do the same with your menus, as you're simply comparing object references. (I'm not sure what the type is here, so I simply chose "Menu".)
var menusToCheck = new List<Menu> { menu1, menu2 };
if (!allowedMenus.Contains(menu))

You can use this extension-method:
public static class EqualsAnyExtension
{
public static bool EqualsAny<T>(this T value, params T[] items)
{
return items.Contains(value);
}
}
Use it like this:
if (condition1 != asd && !menu.EqualsAny(menu1, menu2))

No, you can't do this like the second statement. Because
menu != (menu1 && menu2)
Would mean "compare menu with boolean AND operation on menu1 and menu2".
While
menu != menu1 && menu != menu2
means "apply AND operation to results of comparison operation on menu and menu1 and comparison operation on menu and menu2".

The logical operators yield boolean results. Therefore:
(menu1 && menu2)
evaulates to true or false depending on what the values of the variables are.
If menu1 or menu2 are not boolean then you'll need to do a comparison to yield a boolean, as you did in your first go:
if(condition1 != asd && menu != menu1 && menu != menu2)

You have not specified the data type of menu and the answer could depend on that.
For example if menu,menu1 and menu2 are all boolean then this could make some logical sense
if(menu != (menu1 && menu2))
(amounts to if menu1, menu2 and menu are all the same boolean value)
However if they are strings (or in fact anything other than booleans), then it does not make sense. You could still shorten it, but I wouldn't recommend it for 2 items:
var menuItems = new string[]{menu1,menu2}
if(condition1 != asd && menuItems.Contains(menu))
{
...
}

(menu1 && menu2)
in
if(condition1 != asd && menu != (menu1 && menu2))
both menu1 and menu2 need to be of bool type otherwise it throws
CS0019: Operator '&&' cannot be applied to operands of type
I think it cannot be shortened anymore unless all of them are boolean values, when you can use XOR operator between menu1 and menu2.

var menusToCheck = new List<Menu> {"abc","def","eee","sdds" };
if (!menusToCheck .Contains(menu))
{
..spin..
}
Like this.

Related

Best way to check several conditions on a Textbox.Text

I'm done with my current project and currently trying to improve the code itself.
In the app I developped, when the user clicks the "print" button, the different text in the textboxes are verified for things like is it null or empty ? is it numeric ?
My problem is that I end up with monster lines of code like
if (!String.IsNullOrEmpty(textBoxNbPieces.Text) && !String.IsNullOrEmpty(textBoxNbLotTrempe.Text) && !int.TryParse(textBoxNbPieces.Text, out numero) && !int.TryParse(textBoxNbLotTrempe.Text, out numero))
{
if (int.Parse(textBoxNbPieces.Text) < int.Parse(textBoxNbLotTrempe.Text))
{
erreur++;
}
}
How could I avoid that ?
You dont need to check IsNullOrEmpty and also int.TryParse, the latter includes the former.
bool valid = int.TryParse(textBoxNbPieces.Text, out int pieces)
&& int.TryParse(textBoxNbLotTrempe.Text, out int trempe)
&& pieces >= trempe;
if(!valid) erreur++;
[disclaimer: C#7 syntax]

Compare multiple values in one condition [duplicate]

This question already has answers here:
Equality comparison between multiple variables
(14 answers)
Closed 7 years ago.
Int32 int1, int2, int3 = 123;
Given the above variables, how can I test that all of my variables have the value 123 without creating a collection to perform some Any or something on?
What I've Tried
if(int1 == int2 == int3 == 123)
{
// Fantastic code here
}
EDIT
I must apologise, I haven't been clear enough in my question. I'm fully aware of the && operator, I was asking with regard to 'elegance', i.e. how can I avoid repeating the value I want to compare against.
In the same way I have assigned all 3 integer variables the same value in one hit, I'd like to now make the comparison. It's looking as though there is no way of doing this, so far. I think I'm asking the impossible, I'll have to stick to the basic syntax and keep it simple.
You can create an usefull extension function:
public static bool EqualsAll<T>(this T val, params T[] values)
{
return values.All(v => v.Equals(val));
}
call it like:
bool res = 123.EqualsAll(int1,int2,int3);
You could try something like this, using the logical and operator:
if(int1 == 123 &&
int2 == 123 &&
int3 == 123)
{
}
if(int1 == 123 && int2 == 123 && int3 == 123) { // Code }
What your trying to achieve isn't possible the way you do it.
You have to separate it with &.
if(int1 == something && int2 == something && int3 == 123)
{
// Fantastic code here
}
This is how you should do it using && operator. You can check multiple conditions using this.
UPDATE :
As far as checking multiple values at one go is concerned, you can try making an array out those values and just fire a simple LINQ statement like this to check all of them for a particular value :
if (new[] { int1, int2, int3 }.All(x => x == 1))
Dont know if this fits into your requirement, just a suggestion though.

equivalent of Or in C# [duplicate]

This question already has answers here:
Equivalent of Visual Basic's And and Or in C#?
(6 answers)
Closed 8 years ago.
I have the following code:
if (bl != closeButtonLabel)
{
if (bl != minimiseButtonLabel)
{
optionPanel.Controls.Remove(bl);
}
}
Is there a way to do this in 1 if but check the 2 conditions?
At VB it's easy, you place 'Or' and not 'OrElse' but in c# there is only '||'.
Can anyone help me?
You could try the logical AND operator, '&&'.
if (bl != closeButtonLabel && bl != minimiseButtonLabel)
optionPanel.Controls.Remove(bl);
You don't need the logical Or operator here, ||.
Let's say out loud, what you want: bl should be differnt fom closeButtonLabel AND it shoud be different from minimisButtonlabel
if (bl != closeButtonLabel && bl != minimiseButtonLabel) {...}
or if you really want to use OR
if (!(bl == closeButtonLabel || bl == mimimizeButtonLabel)) {...}
(DeMorgan's Laws)
if(bl != closeButtonLabel && bl != minimiseButtonLabel)
{
//do work
}

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

How to check if two string are of the same length?

I want to check if two string are of the same length. I tried the following, but it doesn't work.
string passnew = "1233";
string passcnfrm = "1234";
if((passnew.Length&&passcnfrm.Length)>6 ||(passnew.Length&&passcnfrm.Length)<15)
{
// ...
}
Why does it not work? What do I need to change?
if(passnew.Length == passcnfrm.Length &&
passnew.Length > 6 && passnew.Length < 15)
{
// do stuff
}
You are missing some basic syntax lessons. What you write inside of these brackets are conditions. We have unary operators (operating on one thing), binary operators (two) and one tertiary operator (forget about that one).
You cannot construct something like your "boundary test" with those easily.
A possible way:
(passnew.Length > 6) && (passcnfrm.Length > 6)
But you aren't testing if the length is equal anyway, even if you could use a syntax like that. You seem to want to compare if both are longer than 6 chars and shorter than 15 chars. One at 7 and one at 14 would satisfy both conditions..
if(passnew.Length == passcnfrm.Length &&
(passnew.Length < 15 && passnew.Length > 6))
{
// ...
}
Checks both are same length, and either one is more than 6 and less than 15 characters long.
that would be:
if(passcnfrm.Length.Equals(passnew.Length))
{
//do stuff
}
A probably better way to do it is:
if (( passnew != null && passcnfrm != null )
( passnew == passcnfrm )
&& ( passnew.Length > 6 && passnew.Length < 15 ))
{
// do stuff
}
Hides the length check inside the equality check which you'll probably need, it isn't in your question but the variable names make it pretty clear you're doing a password change function there. I added the null check to make sure the length checks don't throw a NullReferenceException, not needed in the example because you assign both manually, but might save some trouble if you're going to convert this to a method later on.
You can use like this:
if (s.Contains(s1[i]))
or:
boolean equalsIgnoreCase(String anotherString);
or use this method:
public static int occurrence(string [] a, string a2)
{
int occ = 0;
for (int i = 0; i < a.Length;i++ )
{
if(a[i].Equals(a2))
{
occ++;
}
}
return occ;
}

Categories

Resources