Use of switch with logic operators on C# [duplicate] - c#

This question already has answers here:
'||' operators to be used between two enums in a switch statement
(1 answer)
How to use && operator in switch statement based on a combined return a value?
(5 answers)
c# - case statement for logical operators
(2 answers)
Closed 1 year ago.
I'm C# beginner. Why appear the error (Compiler Error CS0152, A label was repeated in a switch statement. The switch statement contains multiple cases with the value of tag '6') in "case 6:" line, when I write this code:
namespace ConsoleApp1
{
class Class1
{
public int abc { get; set; }
public Class1()
{
}
public void mTest(int aVal)
{
switch(aVal)
{
case (2 | 4):
{
break;
}
case 5:
{
break;
}
case 6:
{
break;
}
}
}
}
}

You're almost there, but the correct way to pattern match that condition is:
case 2 or 4:
break;

Related

C# Pattern matching on type parameter Itself [duplicate]

This question already has answers here:
Switching on type with a generic return type
(2 answers)
Can I use pattern matching for code like this (on generic types) [duplicate]
(1 answer)
Closed 1 year ago.
I have to write this code, with a switch on strings to check for typeof(T):
public bool ContainsKey<T>(Guid id)
{
string ip = httpContext.HttpContext.Connection?.RemoteIpAddress.ToString();
switch (GetLastPartOfClassService<T>())
{
case "Cart":
return Carts.ContainsKey((ip, id));
case "IsAuthenticatedModel":
return Auths.ContainsKey((ip, id));
default:
return false;
}
}
public string GetLastPartOfClassService<T>()
{
string fullClass = typeof(T).ToString();
return fullClass.Substring(fullClass.LastIndexOf('.') + 1);
}
There is no parameter value to use for pattern matching so I used a switch for checking strings, How to replace this with a strongly typed pattern matching. meaning, using Cart instead of "Cart"?

Scope of locals in switch statement [duplicate]

This question already has answers here:
Variable declaration in a C# switch statement [duplicate]
(7 answers)
Case Statement Block Level Declaration Space in C#
(6 answers)
Closed 3 years ago.
I was surprised to discover that locals in switch statements are scoped to the switch statement and not to the case. Why is that? And is it good practice to add curly braces around each case as a workaround.
This won't compile:
switch (n)
{
case 1:
var i = 1;
Console.WriteLine(i);
break;
default:
var i = 2;
Console.WriteLine(i);
break;
}
This does compile:
switch (n)
{
case 1:
{
var i = 1;
Console.WriteLine(i);
break;
}
default:
{
var i = 2;
Console.WriteLine(i);
break;
}
}
This is a design choice specifically made by C#.
A variable only exists inside the innermost braces in which the variable is first declared. This makes it easy to check the variables scope just by looking, and I might guess it also makes parsing easier

Multiple variables in switch-case statement [duplicate]

This question already has answers here:
Multi-variable switch statement in C#
(13 answers)
Closed 8 years ago.
Is it possible to return result from multiple switch statement?
For example i would like to use employee.DepartmentID and employee.StatusID for my case. But how do i include employee.StatusID in this statement? Using and/or operators?
switch (employee.DepartmentID)
{
case 1:
EMAIL = "abc#gmail.com";
break;
case 2:
EMAIL = "abcd#gmail.com";
break;
}
What you really need is this.
Use the Switch to determine which department is involved
Switch (DepartmentID)
{
case 1:
Email = classHR.GetEmailAddress(Status);
break;
case 2:
Email = classMarketing.GetEmailAddress(Status);
break;
}
Use Static Classes for the different departments (using an interface preferably).
This will give you a better run down than what you are thinking of here.

Default Enum type, why this code does not compile? [duplicate]

This question already has answers here:
Why do I have to cast enums to int in C#?
(3 answers)
Closed 9 years ago.
I defined an Enum. I also have 2 methods:
method 1 - will get the enum type - enum default type is int so it will print System.Int32
method 2 - will have switch case that compare the enum type with simple number - so in case the enum is int the switch case need to be compile with not problem and without any casting.
But this code does not compile and I get two errors ( the error point on the case 1 and case 2 in the switch case )
Cannot implicitly convert type 'int' to 'Color'. An explicit conversion exists (are you missing a cast?)
Someone can explain why I get an error even if the Color type is int ?
To compile this code I need to make casting to the Color to int.
The code:
public enum Color
{
RED, // 0
BLUE, // 1
GREEN // 2
};
Color color = Color.BLUE;
private void boo(object sender, EventArgs e)
{
string str = Enum.GetUnderlyingType( color.GetType() ).ToString();
// it will print 'System.Int32'
System.Console.WriteLine(str);
}
// the switch case make the compile error - but the color is int
private void foo()
{
switch( color )
{
case 0:
{
}
break;
case 1:
{
}
break;
case 2:
{
}
break;
}
}
Your code needs to be either:
switch( color )
{
case Color.RED:
break;
...
}
or
switch ( (int)color)
{
case 0:
break;
...
}
You can directly check with Enum Types
Try This:
private void foo()
{
switch( color )
{
case Color.RED:
{
}
break;
case Color.GREEN:
{
}
break;
case Color.BLUE:
{
}
break;
}
}

C#'s switch statement is case-sensitive. Is there a way to toggle it so it becomes case-insensitive? [duplicate]

This question already has answers here:
How to make C# Switch Statement use IgnoreCase
(12 answers)
Closed 9 years ago.
C#'s switch() statement is case-sensitive. Is there a way to toggle it so it becomes case-insensitive?
==============================
Thanks,
But , I don't like these solutions;
Because case conditions will be a variable , and I don't know if they ALL are UPPER or lower.
Yes - use ToLower() or ToLowerInvariant() on its operands. For example:
switch(month.ToLower()) {
case "jan":
case "january": // These all have to be in lowercase
// Do something
break;
}
You can do something like this
switch(yourStringVariable.ToUpper()){
case "YOUR_CASE_COND_1":
// Do your Case1
break;
case "YOUR_CASE_COND_2":
// Do your Case 2
break;
default:
}
Convert your switch string to lower or upper case beforehand
switch("KEK".ToLower())
{
case "kek":
CW("hit!");
break;
}

Categories

Resources