I'm trying to assign a boolean a false value if the int value day is the 31st, and the int value month is any of the following, 4,6,9,11.
What I currently have is not working, how should it be structured?
if (day == 31 && month == 4 || month == 6 || month == 9 || month == 11)
{
validity = false;
}
Granted, I could go on about operator precedence (which one goes first), but really, you should never have to worry about that because you should always be very explicit about how you want something to be evaluated. Use your parentheses to do so.
You can use newer features of C# to make it even more clear what you're doing:
if ((day is 31) && (month is 4 or 6 or 9 or 11))
All answers are valid, but here is my example if you want to shorten expression, what if you need to compare more month values, you can put all values in array and search if month value is contained in array.
if(day == 31 && new int[] { 4, 6, 9, 11 }.Contains(month))
{
}
Also you can create extension method name In and check if your month value is contained in array.
public static class Extensions
{
public static bool In<T>(this T value, params T[] array)
{
return array.Contains(value);
}
}
if (day.In(31) && month.In(4, 6, 9, 11))
{
}
But as I said this depends on you, use what is more readable to you or someone else who look at your code :)
Related
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.
I have the following integer that I would like to check the value with an if statement.
int myInt = 3;
I tried this code which works, but I don't like having to write the variable name over and over.
if (myInt == 0 || myInt == 2 || myInt == 3 || myInt == 4)
{
Debug.WriteLine("Match");
}
else
{
Debug.WriteLine("No Match");
}
To demonstrate what I would like to ideally have, I tried something like this:
if (myInt == (0 | 2 | 3 | 4))
{
Debug.WriteLine("Match");
}
else
{
Debug.WriteLine("No Match");
}
But this doesn't work because the | is not quite the right operator because there is a type mismatch.
I then tried this, which also worked fine, but I still don't like having to declare an extra array.
if ((new int[] { 0, 2, 3, 4 }).Contains(myInt))
{
Debug.WriteLine("Match");
}
else
{
Debug.WriteLine("No Match");
}
The question is:
Is there an operator that can satisfy what I'm trying to accomplish without declaring an additional array or asking for the same variable name over and over with the || operator?
Your question is
Is there an operator that can satisfy what I'm trying to accomplish without declaring an additional array
but it really should be
Is there an operator that can satisfy what I'm trying to accomplish without declaring an additional array every time
There is nothing wrong with having that array once (and initializing it once), but there is a lot wrong with allocating it (and by extension GCing it later) every single time. So You need to declare an array once, something like
private static int matchArray[] = new int[] { 0, 2, 3, 4 };
and later just
if (matchArray.Contains(myInt)) ...
EDIT
If your match array is small, by any means use the answer by #JohnField and not this one - I stand corrected!
There is possibly a way to achieve what you want to do. They are called enum flags. Here there is a nice answer that explains how they work.
They way you want to use integers remind me of an enum where you have possibly multiple choices. Let's take the following case for instance:
[Flags]
enum DaysOfTheWeek
{
Sunday = 1,
Monday = 2,
Tuesday = 4,
Wednesday = 8,
Thursday = 16,
Friday = 32,
Saturday = 64
}
you can declare a variable as follow:
DaysOfTheWeek daysOfTheWeek;
daysOfTheWeek = DaysOfTheWeek.Monday | DaysOfTheWeek.Wednesday | DaysOfTheWeek.Friday;
and then check if your enum contains one of the values assigned above:
if((daysOfTheWeek & DaysOfTheWeek.Monday) == DaysOfTheWeek.Monday)
{
// Contains Monday!
}
else
{
// DOES NOT Contain Monday!
}
or from .NET 4 onwards:
if(daysOfTheWeek.HasFlag(DaysOfTheWeek.Monday))
{
...
}
Clearly this method is more elegant as long as you need to check for a small number of cases. If you have big array to check against, it would not be a suitable approach.
See, I'm just thinking... why not use a switch?
https://msdn.microsoft.com/en-us/library/06tc147t.aspx
int myInt = 3;
switch (myInt)
{
case 0:
case 2:
case 3:
case 4:
// Match
break;
default:
// No match
break;
}
If your array is in order, Array.BinarySearch will be more efficient than Contains, especially if the array has more than a few elements.
if (Array.BinarySearch(checkArray, myInt) >= 0)
;//match
else
;//no match
Usually, however, the best choice for the Contains operation is the HashSet. Thanks to JohanLarsson for pointing that out.
You could use a switch-case, but it could be argued that this looks messy.
switch (myInt)
{
case 0: //Add a comment to make it clear that
case 2: //this is a deliberate fall-through and
case 3: //not a mistake. (E.g. "//Deliberate
case 4: //fall-through for 0, 2, 3, 4")
//Insert code here in this section to do something
Debug.WriteLine("Match");
break; //Break statement is required to indicate end of section
default:
//The default section runs like an "else" statement
//It is optional and will run if none of the above
//cases are applicable.
Debug.WriteLine("No Match");
break;
} //end switch-case
I know I can do it like this:
if(myint == 1 || myint == 2 || myint ==3) //etc...
But I feel like there must be a more efficient way to code this. Is there a way to possibly make a statement like this work?
if(myint.Contains(1 || 2 || 3 || 4))
you can do inverse
new List<int>{1,2,3,4}.Contains(myInt)
Note that there is also Enumerable.Any, but Contains would work for .net 2.0 too.
Close, try the following.
It will take a collection and return true if your int is in the collection:
if (new[] { 1, 2, 3, 4 }.Contains(myint))
//Do something
new[] { 1, 2, 3, 4 } represents an array of integers.
The Contains method is an extension of IEnumerable<T> and will be available to anything that implements it.
How can I test if value of int is for example 1,2,4 or 5? I thought i could do something like this but apparently not.
if(someInt == (1||2||4||5))
Use LINQ:
if ((new[] {1,2,4,5}).Contains(someInt))
Write an extension method
static class MiscExtensions
{
static bool EqualToAny<T>(this T i, params T[] items)
{
return items.Any(x => x.Equals(i));
}
}
And use it like so
static class Program
{
static void Main(string[] args)
{
int myNumber = 5;
if (myNumber.EqualToAny(1, 2, 3, 4, 5))
Console.WriteLine("Hello, World");
}
}
As an alternative you can use:
switch(someInt)
{
case 1:
case 2:
case 4:
case 5:
DoYourStuff();
break;
}
There are two ways I can think of.
Or all the comparisons.
if (someInt == 1 || someInt == 2 || someInt == 4 || someInt == 5) {
}
Or for a more flexible solution see if someInt is in an array.
if (Array.BinarySearch(new[] { 1, 2, 4, 5 }, someInt ) != -1) {
}
You need to write your if statement like this
if (someInt==1 || someInt==2 || someInt==4 || someInt==4)
Or you could use a switch statement
switch (someInt)
{
case 1:
case 2:
case 4:
case 5:
// do something
break;
}
Breaking down your attempted code is quite interesting. You wrote:
if(someInt == (1||2||4||5))
I guess in your head you read it as, if someInt equals 1 or 2 or 4 or 5. And if computers behaved like humans then this would work. But we all know that computers don't behave like that!
The == equality operator, a binary operator, returns true when its two operands are equal. So that means, in your version, if it compiled, you would need someInt to be equal to (1||2||4||5). And for that to even be meaningful, we would need (1||2||4||5) to evaluate to a single value, instead of producing a compile error. And, if it did evaluate to a single value, then it could not have the meaning which you want. Because you want the test to return true when someInt is equal to one of four candidate values.
The bottom line is that == tests for exact equality between precisely two values.
You can't do it like that. Instead use:
if(someInt == 1 || someInt == 2 || someInt == 4 || someInt == 5)
Or also you could use something like this:
if((new List<int>() {1,2,4,5}).Contains(someInt) == true)
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;
}