I implemented the code using if...else.. This is working properly.
public static byte GetLengthWithCascadedIfElse(int number)
{
if (number < 10 && number > -10)
{
return 1;
}
if (number > 10 && number < 100)
{
return 2;
}
if (number > 1000000 && number < int.MaxValue)
{
return 3;
}
if (number < -100000000 && number > -1000000000)
{
return 4;
}
return 10;
}
My problem is that I need to implement the code above, using switch expression. I tried! Its dont work.
public static byte GetLengthWithSwitchExpression(int number)
{
return number switch
{
_ when number == 0 && number == -1 => 1,
_ => throw new InvalidOperationException()
};
}
CS0266 Cannot implicitly convert type 'int' to 'byte'. An explicit conversion exists (are you missing a cast?)
Perhaps you're thinking of C# 9's relational patterns?
number switch
{
> -10 and < 10 => 1,
> 10 and < 100 => 2,
> 1000000 and < int.MaxValue => 3,
> -1000000000 and < -100000000 => 4,
_ => 10
};
Or C# 8's when?
number switch
{
int a when a > -10 && a < 10 => 1,
int a when a > 10 && a < 100 => 2,
int a when a > 1000000 && a < int.MaxValue => 3,
int a when a > -1000000000 && a < -100000000 => 4,
_ => 10
};
Your stab at the conversion seems to use totally different parameters to what you say want/works.. so I didn't try to convert "the case of 0 and 1"
I did wonder if your "less than int.maxvalue" is redundant? Or will you really have a maxvalue passed in, and want it to be 10?
Convert if statement to switch statement or switch expression from visualstudio
This refactoring applies to:
C#
What: Convert an if statement to a switch statement or to the C# 8.0 switch expression.
When: You want to convert an if statement to a switch statement or a switch expression and vice versa.
Why: If you are using an if statement, this refactoring enables an easy transition to switch statements or switch expressions.
How-to
1-Place your cursor in the if keyword.
2-Press Ctrl+. to trigger the Quick Actions and Refactorings menu.
3-Select from the following two options:
Select Convert to 'switch' statement.
enter image description here
Select Convert to 'switch' expression.
enter image description here
Related
I been searching for some information about if statements with multiple conditions but haven't found something that corresponds to myquestion.
I was wondering if you could write:
int n = 3
if (3 < n < 20)
{
//do something..
}
rather than doing:
if (n > 3 && n < 20)
{
//do something..
}
The first statement doesn't work for me which i think it should, because it's plain simple.
Maybe someone can give me the correct syntax for doing so or maybe it's just impossible at all and i just have to go with the AND.
To explain why it's invalid:
if (3 < n < 20)
Could be rewritten as:
if ((3 < n) < 20)
Now 3 < n's outcome would be a bool.
So basically you'll get:
if (true/false < 20)
Which is not valid in C#.
Stefan's answer explains why it's impossible.
But here is a workaround, if you don't want to write that pesky && explicit conditions every time - you can create an extension method:
public static class IComparableExtensions
{
public static bool Between<T>(this T self, T low, T high) where T : IComparable
{
return self.CompareTo(low) > 0 && self.CompareTo(high) < 0;
}
}
And use it like this:
int n = 5;
if(n.Between(3, 20))
{
// do your stuff here
}
Please note, however, that this might be confusing - since Between doesn't specify if the compare is inclusive, exclusive, or inclusive in only one direction - so if you compare, say, 20.Between(10, 20) - should it return true or false?
A better approach would require adding another variable to the method, to indicate that:
[Flags]
public enum CompareMode
{
Exclusive = 0,
IncludeLow = 1,
IncludeHigh = 2,
Inclusive = IncludeLow | IncludeHigh
}
public static class IComparableExtensions
{
public static bool Between<T>(this T self, T low, T high, CompareMode mode) where T : IComparable
{
var compareLow = (mode & CompareMode.IncludeLow) == CompareMode.IncludeLow ? 0 : 1;
var compareHigh = (mode & CompareMode.IncludeHigh) == CompareMode.IncludeHigh ? 0 : -1;
return self.CompareTo(low) >= compareLow && self.CompareTo(high) <= compareHigh;
}
}
Now you use it like this:
if(n.Between(3, 20, CompareMode.Exclusive))
{
// do your stuff here
}
You can see a live demo on rextester.
This way, another person reading this code (or even you, 6 months from now) will know immediately, without having to look inside the Between extension method, if between is inclusive, exclusive, or whatever.
Generally it is not possible what you want to do.
but in your logic if you want to perform single liner logic you can use ternary operator.
for eg. you need to assign value of n to variblae result else it should be 0 as default.
int result = n > 3 ? (n < 20 ? n : 0) : 0
it is equivalent to
int result = 0;
if (n > 3 && n < 20)
{
result = n;
}
I'm making a game in unity, and I have this 'if statement' that by every 5 waves my shop menu will become visible. The code does work, but I am certain I'm doing something wrong or could do something better!
if (waveCount == 5 || waveCount == 10 || waveCount == 15 || waveCount == 20 || waveCount == 25 || waveCount == 30 || waveCount == 35 || waveCount == 40 || waveCount == 45 || waveCount == 50)
{
// yield return new WaitForSeconds(shopWait);
shopPanel.SetActive(true);
}
As you can see the 'if statement' not that good, normally it continues all the way to waveCount == 100 but i cut that out. There must be a simpler or cleaner way to do this :/ but i just can't wrap my head around it :(
Edit 1:
Thanks, I didn't know much about modulo, know I know what I have to read about :)
You can use modulo operation:
if (waveCount % 5 == 0)
Yes, there are indeed simpler ways of doing this. If you use a little bit of maths and logic, you can figure this out.
Since you want to check whether the value of waveCount is a multiple of 5, you can use % to get the reminder of waveCount / 5. If that reminder is 0, waveCount is a multiple of 5.
if (waveCount % 5 == 0 && waveCount <= 100)
I added waveCount <= 100 to replicate your code's behaviour when waveCount is larger than 100 i.e. not get into the if statement.
Alternatively, you can put all the values into a list:
var list = new List<int>();
for (int i = 1 ; i <= 20 ; i++) {
list.Add(i * 5);
}
And then check whether the list contains the number:
if (list.Contains(waveNumber))
The advantage of this is that if you decided to change how the game works and say that the shop menu can be opened at waves 9, 52, and 77, you just add the numbers to the list, without modifying the if statement. This provides a lot of flexibility.
if (waveCount % 5 == 0 && waveCount <= 50) {
//...code
}
If your “if” statement's body just contains shopPanel.SetActive(true); you can do that without even using “if” like that.
shopPanel.SetActive(waveCount % 5 == 0 && waveCount <= 50);
Give it a try
if (waveCount % 5 == 0 && waveCount <= 50)
Use the modulo-operator:
if(waveCount % 5 == 0 && waveCount <= 100) ...
The operator calculates the remainder of an integer-divison. In your case the statement should return zero indicating that your number divided by 5 has no remainder.
Just to generalize: in case the data you have doesn't match a pattern, you can put all the things to match against in a set, then test the set for membership:
var thingsToMatch = Set(2, 5, 8, 14, 23, 80, 274...);
if (someNumber in thingsToMatch) {...}
As long as you know the set isn't being recreated everytime the function is called, this has proven to be fairly fast. If your language doesn't automatically cache the set, you can make it a static variable of the function.
You can use the remainder operator for this:
if (waveCount % 5 == 0 && waveCount > 0 && waveCount <= 50)
{
//yield return new WaitForSeconds(shopWait);
shopPanel.SetActive(true);
}
You can test whether the remainder of the division by 5 is 0, which means that the number is divisible by 5.
if (waveCount % 5 == 0 && waveCount >= 5 && waveCount <= 50)
C# performs integer math on integer number types (int, long, uint, ...).
Example:
13 / 5 = 2
I.e. you never get a decimal fraction part. The complementary operation is the modulo operation. It gives you the remainder of this division:
13 % 5 = 3
I.e., 13 / 5 is 2 plus remainder 3. Together, division and modulo operation allow you to perform the reverse operation.
(5 * (13 / 5)) + (13 % 5) =
(5 * 2 ) + ( 3 ) = 13
If you have irregular figures, quite different approaches are to use a switch statement:
switch (waveCount) {
case 5:
case 10:
case 15:
case 20:
case 25:
case 30:
case 35:
case 40:
case 45:
case 50:
shopPanel.SetActive(true);
break;
}
or an array of allowed values:
private static readonly int[] AllowedValues =
new int[] { 5, 10, 15, 20, 25, 30, 35, 40, 45, 50 };
if(Array.IndexOf(AllowedValues, waveCount) >= 0) { ... }
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 6 years ago.
Improve this question
The basic idea we follow is
if (i > 0 && i < 100) {
} else if (i > 100 && 1 < 150) {
}
This is the basic idea for range check..
Is there any good way to check these type of conditions.
Thanks in advance for the help!
int endX=200;
Click on below link you will get what is the difference #Steve
var switchCond = new Dictionary<Func<int, bool>, Action>
{
{ x => x <= 290 , () => endX=244 },
{ x => x <= 530, () => endX=488 },
{ x => x <= 790 , () => endX=732 },
{ x => x <=1000 || x > 976 , () => endX=976 }
};
switchCond.First(sw => sw.Key(endX)).Value();
[Switch case: can I use a range instead of a one number
use ternary operator
var range =
i < 100? "Range1":
i < 150? "Range2":
i < 200? "Range3":
i < 250? "Range4":
i < 300? "Range5":
"Range6";
This is example only to show technique. obviously, you must adapt it to your code objectives and appropriate range definitions. (by the way, in your example, using if- else if, your code misses the value 100. you need to decide which range 100 should be included in, and change one of the inequality operators to either <= or >=.
you could have switch construct "handle" ranges by use of a List of your bounds:
List<int> bounds = new List<int>() {int.MinValue, 0, 100, 150, 200, 300, int.MaxValue };
switch (bounds.IndexOf(bounds.Last(x => x < j)))
{
case 0: // <=0
break;
case 1: // > 0 and <=100
break;
case 2: // > 100 and <= 150
break;
case 3: // > 150 and <=200
break;
case 4: // > 200 and <=300
break;
case 5: // >300
break;
}
where you may have to add some additional checks to
I was writing a program which takes input from the keyboard and prints a square matrix in the following spiral manner
1 2 3
8 9 4
7 6 5
I managed to write the program but I encountered a weird error.
in line 26 it gives me an index out of bound exception
while (matrix[row, col] == 0 && col < matrix.GetLength(0) )
However if I switch the order of the two statements inside the loop the exception is gone ? Does this mean that the order of the two statements in the while loop is important ? And if yes , why ? Shouldn't it be if both statements are true to execute the loop, and if one of them is false, no matter which one, to stop executing it.
Here is my code:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace SpiralMatrixN
{
class Program
{
static void Main(string[] args)
{
//prompt the user to enter n
Console.WriteLine("Enter the value of n");
int n = int.Parse(Console.ReadLine());
int[,] matrix = new int[n,n];
Console.Clear();
System.Console.SetWindowSize(100, 30);
int value = 1;
int col = 0;
int row = 0;
if (n>0 && n<21)
{
while(value <= n*n)
{
while (matrix[row, col] == 0 && col < matrix.GetLength(0) )
{
matrix[row, col++] = value;
value++;
}
col--;
row++;
while (row < matrix.GetLength(1) && matrix[row, col] == 0)
{
matrix[row++, col] = value;
value++;
}
row--;
col--;
while (col >= 0 && matrix[row, col] == 0 )
{
matrix[row, col--] = value;
value++;
}
col++;
row--;
while (matrix[row, col] == 0 && row >= 0)
{
matrix[row--, col] = value;
value++;
}
col++;
row++;
}
for (int i = 0; i < matrix.GetLength(0); i++)
{
for (int j = 0; j < matrix.GetLength(1); j++)
{
Console.SetCursorPosition(j * 5, i * 2);
Console.Write(matrix[i, j] + " ");
}
Console.WriteLine();
}
}
}
}
}
Yes, order is important. Conditions in the && clause are executed in the order of precedence, and if one fails another is not executed. Currently what you have fails because matrix[row, col] == 0 is executed first, and col comes out of bounds. So your check for col (which is absolutely correct btw) should come first:
while (col < matrix.GetLength(0) && matrix[row, col] == 0)
If it fails, second statement won't be executed and you won't have an error. This is called "short-circuit evaluation".
Yes, it is called short circuit evaluation. Since you are using "&&", the second condition gets evaluated only after the first one evaluates to true.
The order in && is important && uses short-circuiting vs & which does not. In an && expression from left to right if a condition is false the other conditions are not evaluated.
Conditional logical operators
The && and || operators are called the conditional logical operators.
They are also called the "short-circuiting" logical operators.
conditional-and-expression:
inclusive-or-expression
conditional-and-expression && inclusive-or-expression
conditional-or-expression:
conditional-and-expression
conditional-or-expression || conditional-and-expression*
The && and || operators are conditional versions of the & and |
operators:
The operation x && y corresponds to the operation x & y,
except that y is evaluated only if x is true.
The operation x || y corresponds to the operation x | y, except that y
is evaluated only if x is false.
An operation of the form x && y or x || y is processed by applying
overload resolution (Section 7.2.4) as if the operation was written x
& y or x | y. Then,
If overload resolution fails to find a single best
operator, or if overload resolution selects one of the predefined
integer logical operators, a compile-time error occurs.
Otherwise, if the selected operator is one of the predefined Boolean
logical operators (Section 7.10.2), the operation is processed as
described in Section 7.11.1.
Otherwise, the selected operator is a user-defined operator, and the
operation is processed as described in Section 7.11.2.
It is not possible to directly overload the conditional logical operators.
However, because the conditional logical operators are evaluated in
terms of the regular logical operators, overloads of the regular
logical operators are, with certain restrictions, also considered
overloads of the conditional logical operators. This is described
further in Section 7.11.2.
From MSDN C# Conditional Operators
The && and || operators are known as "shortcut short-circuit operators"; the second half is only evaluated if necessary. This is useful for two reasons:
It's more efficient during execution since less code is run (not usually much more, but if you're doing IO or something it could be), and
It's convenient for programming since you can use the first half as a precondition to the second half even being evaluated. Such as,
if (myObj != null && myObj.Name == "something")
If both halves were evaluated above, you'd get an error from myObj.Name whenever myObj was null.
If you do need both halves of the expression evaluated no matter what, you can use the & or the | operators. I find I rarely do.
MSDN: && Operator (C# Reference)
I have an if statement as follows
if (1 <= value <= 20)
{
}
value is a double.
however I get an error which says that "Operator '<=' cannot be applied to operands of type 'bool' and 'double'"
Is there a way around this error?
C# doesn't allow you to do this.
Do like this:
if (1 <= value && value <= 20)
The problem is not the double, problem is your syntax is incorrect.
You:
if (1 <= value <= 20)
{
}
That is interpreted as
(1 <= value) <= 20
so first 1 will be compared with value and it will be determined if the former is "less than or equal" the latter. That gives a boolean. Then that boolean, True or False, is compared with <= to 20. But you cannot ask if True/False is less than or equal 20, in C#.
Problem : you can not check two expressions without Combining them.
Solution : i think you want to check whether value is in beteween 1 and 20
You can Use Logical AND && operator for checking this
Try This:
if (value >= 1 && value <= 20)
{
}
1 <= value evaluates out to be bool (false if value is less than 1 and true otherwise).
So it evaluates out to be (true <= 20) or (false <=20) and error states clearly that you cannot use operator <= to compare bool and double.
You need and (&&) operator to do comparison:
if (1 <= value && value <= 20)
{
}