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 8 years ago.
Improve this question
How to handle multiple values inside one case? So if I want to execute the same action for value "first option" and "second option"?
Is this the right way?
switch(text)
{
case "first option":
{
}
case "second option":
{
string a="first or Second";
break;
}
}
It's called 'multiple labels' in the documentation, which can be found in the C# documentation on MSDN.
A switch statement can include any number of switch sections, and each section can have one or more case labels (as shown in the string case labels example below). However, no two case labels may contain the same constant value.
Your altered code:
string a = null;
switch(text)
{
case "first option":
case "second option":
{
a = "first or Second";
break;
}
}
Note that I pulled the string a out since else your a will only be available inside the switch.
It is possible
switch(i)
{
case 4:
case 5:
case 6:
{
//do someting
break;
}
}
You may be better off using just an if statement if you want to be able to treat both together and separate as distinct cases:
if (first && second)
{
Console.WriteLine("first and second");
}
else if (first)
{
Console.WriteLine("first only");
}
else if (second)
{
Console.WriteLine("second only");
}
Related
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 1 year ago.
Improve this question
I'm currently learning C# and I'm having troubles. I'm getting cannot convert from 'double' to 'System.ReadOnlySpan<char>' error when I try to use !double.TryParse
static double userDouble, correctDouble;
static void someMethod() {
Console.Write(someStringOfDoubles);
while(!double.TryParse(userDouble, out _)) {
try {
userDouble= Double.Parse(Console.ReadLine());
}
catch {
Console.WriteLine($"{Convert.ToString(userDouble)} is an invalid input\n\n");
}
}
// checks if the userDouble is correct or not.
if (Math.Round(correctDouble, 2) == userDouble) {
Console.WriteLine("You are Correct!\n");
}
else {
Console.WriteLine("You are Incorrect.");
}
}
What should it do: Check if userDouble is a valid double and not letter(s)/word(s).
I also tried:
while(!double.TryParse(Console.ReadLine(), out userDouble)) {
Console.WriteLine($"{Convert.ToString(userDouble)} is an invalid input\n\n");
}
but this gives me No overload for method 'TryParse' takes 1 arguments
Any help would be much appreciated!
You need to get console value in string variable first then check it with double.TryParse(...). Try like below.
string s = Console.ReadLine();
while(!double.TryParse(s, out userDouble)) {
Console.WriteLine($"{s} is an invalid input\n\n");
s = Console.ReadLine();
}
Below attempt of yours must work without any error. But only problem you will face is it will write 0 is an invalid input for evert input because double.TryParse will set userDouble = 0 when value from Console.ReadLine() are not double.
while(!double.TryParse(Console.ReadLine(), out userDouble)) {
Console.WriteLine($"{Convert.ToString(userDouble)} is an invalid input\n\n");
}
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
i'm making simple name generator, and it's working like that: I got an array with name values it's 4 elements, and i'm using random class to pick specific name from array, and next i'm using switch case to validate which one is picked and print it to console.
But, it's only 4 element, but what when i'll try to make 100 elements 4example? I've tried to make switch case in for loop to increment everything in one case, but it turns out that case index should be const. Well, is there any other possible way to make switch case more flexible, and smaller?
Here's code for intersed http://pastebin.com/bbCxLtRq
There is no switch needed:
if (NameIndex >= 0 && NameIndex <= 3)
{
return Name[NameIndex];
}
return null;
With more complex examples, you can use return to get rid of break.
Instead of
switch (NameIndex)
{
case 0:
name = Name[0];
break;
case 1:
name = Name[1];
break;
case 2:
name = Name[2];
break;
case 3:
name = Name[3];
break;
}
return name;
write
switch (NameIndex)
{
case 0:
return Name[0];
case 1:
return Name[1];
case 2:
return Name[2];
case 3:
return Name[3];
}
return null;
As mentioned in the comments, there is NO need for Switch statement to achieve this goal - refer to the following code snippet as an example:
public class Generate
{
static string[] Name = new string[] { "Mariusz", "Janusz", "Bogdan", "Zbigniew" };
static Random random = new Random();
public static string NameGen()
{
return Name[(int) random.Next(3)];
}
}
In case you really need to use Switch statement (for some reason, may be just for didactic purpose), then there is a way to simplify it like shown in the following snippet:
switch (NameIndex)
{
case 0:
case 1:
case 2:
case 3:
return Name[NameIndex];
}
Hope this may help
Make your methods independents of a fixed length:
public static string NameGen()
{
int index = random.Next(Names.Length);
return Names[index];
}
public static string SurnameGen()
{
int index = random.Next(Surnames.Length);
return Surnames[index];
}
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 7 years ago.
Improve this question
Could you tell me how to use switch with the below mentioned code snippet ?
if (IsSelectedOrganizer)
{
//
}
else if (IsNewOrganizer && IsOrganizerUserAlreadyExist)
{
//
}
else if (IsNewOrganizer && !IsOrganizerUserAlreadyExist)
{
//
}
else
{
//
}
But on Javascript we can do that as shown below.But C# it doesn't allow ? It says A constant value is expected
switch (true) {
case IsSelectedOrganizer:
//
break;
case IsNewOrganizer && IsOrganizerUserAlreadyExist:
//
break;
case IsNewOrganizer && !IsOrganizerUserAlreadyExist:
//
break;
}
That's a perfect use case for an if not for a switch, so i suggest to keep it. But you could improve it a little bit:
if (IsSelectedOrganizer)
{
//
}
else if (IsNewOrganizer)
{
if (IsOrganizerUserAlreadyExist)
{
//
}
else
{
//
}
}
else
{
//
}
A switch statement cannot have multiple conditions in it like if/else does, this is because switch is typically implemented as a fast in-program hashtable which means that: 1) All comparison values must be const, and 2) it doesn't actually perform as many comparisons as there are switch case expressions.
There is a "workaround" that requires converting a boolean expression into a custom enum value and then switching on that, but I don't see how it would be of any help in this situation.
That's not a great candidate for a switch statement as your logic depends on the values of several variable rather than checking a single variable for different values.
Here's an example of the sort of code that's easy to convert to a switch statement:
if (value == 0)
{
// do stuff
}
else if (value == 1)
{
// etc
}
As a switch statement that would be:
switch (value)
{
case 0:
// do stuff
break;
case 1:
// etc
break;
}
There's nothing wrong with using if...else if statements if you're checking combinations of different variables, as you are. If for some reason you have to use a switch statement, the best solution would be to create an enum with values representing each of your possible states, then switch on that. For example:
enum OrganizerType
{
SelectedOrganizer,
NewOrganizerUserExists,
NewOrganizerUserDoesntExist
}
// ...
OrganizerType orgType = calculateOrgType();
switch (orgType)
{
case SelectedOrganizer:
// do stuff
break;
// etc
}
As an exercise purely is "can it be done?", here's a solution. No developer, ever, should consider using this in real life though:
var switchValue = IsSelectedOrganizer ? 4 : 0 +
IsNewOrganizer ? 2 : 0 +
IsOrganizerUserAlreadyExist ? 1 : 0;
switch (switchValue)
{
case 7:
case 6:
case 5:
case 4:
// IsSelectedOrganizer part
break;
case 3:
// IsNewOrganizer && IsOrganizerUserAlreadyExist part
break;
case 2:
// IsNewOrganizer && !IsOrganizerUserAlreadyExist part
break;
default:
// else part
}
public int FlagValues
{
return (IsSelectedOrganizer & 1) + (IsNewOrganizer & 2) + (IsOrganizerUserAlreadyExists & 4)
}
switch (FlagValues)
In no respect better than using ifs but implemented using switchs ;-).
switch (IsSelectedOrganizer)
{
case true:
{
//
}
break;
default:
{
switch (IsNewOrganizer)
{
case true:
{
switch ((IsOrganizerUserAlreadyExist))
{
case true:
{
//
}
break;
default:
{
//
}
break;
}
}
break;
default:
{
//
}
break;
}
}
break;
}
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 7 years ago.
Improve this question
What is the best alternative for a if --else if --block that contains many if statements.
code:
string word="";
if(letter=='a')
{
// do some action
call(a);
}
else if (letter=='b')
{
call(b)
}
else if (letter=='c')
{
call(c)
}
else if (letter=='d')
{
// do some action
call(d)
}
else if (letter=='e')
{
// do some action
call(e)
}
................
..............
else if (letter=='z')
{
// do some action
call(z)
}
If there are many if-else statements what is the best way to find a solution for such a scenario. Is there a way to effectively design such a scenario using classes/objects?
I am sure many of us would have faced such problems like this during design/coding. Is there a effective way to handle such a situation?
NO SWITCH STATEMENTS PLEASE. AN EFFECTIVE DESIGN ALGORITHM USING C# OBJECTS WOULD BE THE BEST BET.
In C# the most direct translation is a switch statement. While switch is not strictly speaking an object-oriented construct, char is not a proper object in C# either.
switch(letter)
{
case 'a':
call(a);
break;
case 'b':
call(b);
break;
// and so on
}
If the parameter is not a simple value type but rather an object, use a virtual method instead of an explicit control structure. This is the true "object oriented" way to do it: in Smalltalk, ifTrue:, ifFalse: and ifTrue:ifFalse: are methods on Boolean taking code blocks as parameters! C# makes this rather verbose, though.
static class Example {
static void Sample(ISpeaker input) {
input.Speak(); // this call acts like a control structure
}
}
interface ISpeaker {
void Speak();
}
class Cat : ISpeaker {
public void Speak() {
Console.WriteLine("Meow");
}
}
class Dog : ISpeaker {
public void Speak() {
Console.WriteLine("Woof");
}
}
If you are stuck with a simple type, another approach is an explicit dispatch table.
static readonly Dictionary<char, Action> dispatch
= new Dictionary<char, Action> {
{ 'a', () => call(a) },
{ 'b', () => call(b) },
};
static void Process(char letter) {
dispatch[letter]();
}
If your conditions are too complex for a Dictionary-based dispatch table, you can use a List-based linear dispatch table which more closely mirrors the behavior of else-if chains:
static List<KeyValuePair<Func<char, bool>, Action>> dispatch
= new List<KeyValuePair<Func<char, bool>, Action>>() {
{ x => x == 'a', () => call(a) },
{ x => x == 'b', () => call(b) },
{ x => true, () => callDefault() },
};
static void Process(char letter) {
dispatch.First(kvp => kvp.Key(letter)).Value();
}
You can do the following:
private Dictionary<char, Action> _dic =
new Dictionary<char, Action>
{
{'a', (Action)a},
{'b', (Action)b},
...
};
And then
var action = this._dic.TryGetValue(letter);
if (action == null)
{
// this is like default case - no key matched the letter
}
else
{
// call the action associated with the letter
action();
}
https://msdn.microsoft.com/en-us/library/06tc147t.aspx
Do you mean a switch? This is effectivly like a large list of else-ifs
Use switch as an alternative to if...else.
switch offers more readability of your code and is more easy to understand rather that if else where, if you are nesting heavily, it might get difficult to understand and read code.
Also, switch is slightly better on the performance side when compared to if...else.
Hope this helps.
Technically, you picked a more complex way to express a switch statement. Switch statements, in turn, may be considered a "code smell".
If I understand your example correctly, you really only want to vary a parameter on a method call based on the value of some variable. There might not be any good way to improve upon writing your code as switch statement, but maybe using a Dictionary to look up the parameter based on the letter value is an option to consider.
You can use a switch statement.
switch (letter)
{
case 'a':
case(a);
break;
case 'b':
case(b);
break;
...
case 'z':
case(z);
break;
default:
Assert.Fail(letter.ToString() + " was an unexpected value");
break;
}
Use a switch statement:
switch(value)
{
case value == "X":
// handle
break;
case ...
break;
default:
// Doesn't match any case above
break:
}
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 8 years ago.
Improve this question
As question states I am trying to create a way to validate every field on my form. Every field on my form requires the same validation. I thought about creating a method to call to avoid re-writing code. Also for my method not to fail when it is called multiple times. How can I use the valdiations below to create a method or other type of statement for all my field validations?
if (string.IsNullOrEmpty(firstnameTextBox.Text))
{
MessageBox.Show("Please enter a first name");
}
else if (!Int32.TryParse(firstnameTextBox.Text, out number))
{
MessageBox.Show("No numbers allowed for their first name");
}
Possible method
private bool formValidation(string text)
{
int number;
if (string.IsNullOrEmpty(text))
{
MessageBox.Show("Please enter a first name");
}
else if (!Int32.TryParse(text , out number))
{
MessageBox.Show("No numbers allowed for their first name");
}
return true;
}
Problem 1: you are not returning false value when user enters empty string or invalid integer. so irrespective of the input string your method returns true always.
Solution 1: you need to return false value when user enters empty string or invalid integer.
Suggestion : String.IsNullOrEmpty() method only check wether string is null or empty but it doesnot check for whitespaces, here in your code user can enter whitespaces (user inputs from textboxes) which needs to be identified. so i would suggest you to use String.IsNullOrWhiteSpace() instead of String.IsNullOrEmpty() which will check for Null,Empty and whitespace.
Complete Code:
private bool formValidation(string text)
{
int number;
if (string.IsNullOrWhiteSpace(text))
{
MessageBox.Show("Please enter a first name");
return false;
}
else if (!Int32.TryParse(text , out number))
{
MessageBox.Show("No numbers allowed for their first name");
return false;
}
return true;
}
In situations like these, there are two better options so as not to tarnish your code with cross-cutting concerns. I tend to use Attributes that decorate fields / properties or methods in my classes and then have a general inspector read these at runtime.
Another option, similar but probably more robust, is to consider using some Aspect Oriented Programming tool such as PostSharp