The best way to illustrate my question is this C# example:
//It seems that the comment is required:
//I need to change the values of someString0, someString1, or someStringN
//depending on the `type` variable
ref string strKey;
switch(type)
{
case 0:
strKey = ref someString0;
break;
case 1:
strKey = ref someString1;
break;
//And so on
default:
strKey = ref someStringN;
break;
}
//Set string
strKey = "New Value";
Can I do this in C#?
PS. I know that I can do this in a function. I'm asking about an "in-line" approach.
If you really want to do the assignment similar to the way you're asking for, here is one way that doesn't use ref
Action<string> action;
switch (type) {
case 0:
action = newVal => someString0 = newVal;
break;
case 1:
action = newVal => someString1 = newVal;
break;
case 2:
action = newVal => someString2 = newVal;
break;
default:
action = null;
break;
}
if (action != null) action.Invoke("some new value");
Performance-wise, the above takes about 8 nanoseconds longer to execute than the direct alternative below
switch (i) {
case 0:
someString0 = "some new value";
break;
case 1:
someString1 = "some new value";
break;
case 2:
someString2 = "some new value";
break;
default:
break;
}
But you're talking a little longer than next to nothing. On my not particularly fast laptop, the Action version takes around 13 nanoseconds to execute vs. the direct assignment method that takes around 5.5 nanoseconds. Neither is likely to be a bottleneck that matters.
why are you splitting this up into a switch and then an assignment later? why not just set the value in the switch and avoid the ref behavior at all?
string newValue = "new value";
switch(type)
{
case 0:
someString0 = newValue;
break;
case 1:
someString1 = newValue;
break;
//And so on
default:
someStringN = newValue;
break;
}
Why don't you just set the correct string variable like this:
switch(type)
{
case 0:
someString0 = "New Value";
break;
case 1:
someString1 = "New Value";
break;
//And so on
default:
someStringN = "New Value";
break;
}
An even better approach is to replace your n string variables with an array of strings so that the assignment becomes a single line of code:
string[] someString;
someString[type] = "New Value";
Related
I was wondering if I can use a switch with multiple expressions. For example:
string s = "A";
int i = 3;
switch (s, i)
{
case "A", 1:
//DoStuff
break;
case "A", 2:
//DoStuff
break;
case "A", 3:
//DoStuff
break;
...
}
I don't want to use hundreds of if(s == "A" && i == 1)-Statements so it would be great if there's a better solution.
PS: This switch is just an example, I'm actually using it with more complex strings like Names
You certainly can, for example by using tuples:
string s = "A";
int i = 3;
switch (s, i)
{
case ("A", 1):
// DoStuff.
break;
case ("A", 2):
// DoStuff.
break;
case ("A", 3):
// DoStuff.
break;
}
(Basically exactly what you typed, except with the addition of parenthesis in the cases to make them into tuples.)
Note that this requires C# 7 or later.
Since C# 7, it is possible to do the following:
string s = "A";
int i = 3;
switch (s)
{
case "A" when i == 1:
//DoStuff
break;
case "A" when i == 2:
//DoStuff
break;
case "A" when i == 3:
//DoStuff
break;
...
}
I am building a form that takes an input number from a text box and then will take the number that was input, and display the roman numeral equivalent in another text box.
My Form:
private void convertButton_Click(object sender, EventArgs e)
{
int numberInput;
switch (numberInput)
This is where I keep getting an error code. The "switch (numberInput)" is seen as and unassigned local variable. How do I assign it so that it will be able to access all of the case integers?
{
case 1:
outputTextBox.Text = "I";
break;
case 2:
outputTextBox.Text = "II";
break;
case 3:
outputTextBox.Text = "III";
break;
case 4:
outputTextBox.Text = "IV";
break;
case 5:
outputTextBox.Text = "V";
break;
case 6:
outputTextBox.Text = "VI";
break;
case 7:
outputTextBox.Text = "VII";
break;
case 8:
outputTextBox.Text = "VIII";
break;
case 9:
outputTextBox.Text = "IX";
break;
case 10:
outputTextBox.Text = "X";
break;
default:
MessageBox.Show("Please enter and number between 1 and 10. Thank you!");
break;
}
Cause your variable is not assigned yet int numberInput; and so the error. You said input is coming from a TextBox, in that case do like below assuming textbox1 is your TextBox control instance name
int numberInput = Convert.ToInt32(this.textbox1.Text.Trim());
Convert.ToInt32 may throw an exception if the parsing is unsuccessful. Another method is to Int.Parse:
int numberInput = int.Parse(textbox1.Text.Trim());
or better yet
int numberInput;
if(int.TryParse(textbox1.Text.Trim(), out numberInput))
{
switch (numberInput)
...
}
i have problems when adding mullti values into same case:
this is my c# code
string input = combobox1.selectedvalue.ToString();
switch(input)
{
case "one";
return 1;
break;
case "two";
return 2;
break;
case "three" , "four": // error here
return 34;
break;
default:
return 0;
}
need your help for
Just use separate labels:
string input = combobox1.selectedvalue.ToString();
switch(input)
{
case "one":
return 1;
break;
case "two":
return 2;
break;
case "three":
case "four":
return 34;
break;
default:
return 0;
}
See switch:
Each switch section contains one or more case labels followed by one or more statements
You can you the fall though, read this for more information
so it's look like this
switch(input)
{
case "one":
return 1;
break;
case "two":
return 2;
break;
case "three":
case "four":
return 34;
break;
default:
return 0;
}
Right syntax is
case "three":
case "four":
return 34;
break;
instead
case "three" , "four":
return 34;
break;
From switch (C# Reference)
A switch statement includes one or more switch sections. Each switch
section contains one or more case labels followed by one or more
statements.
I hope you can help me! I am trying to make a game similiar to candyland. I want the die to spin when the user clicks the button. A random number is chosen and based on that number, the dice displays the image for that number. That works! Then, I want our user to be able to move forward on our board- based on the spot that they're on, it adds whatever they spinned and the image on that spot becomes visible. When in debug mode, everything works perfectly but for some reason, the pawn never moves! Can you please tell me why. I am attaching my code below. Thank you so much!
protected void btnSpin_Click(object sender, EventArgs e)
{
Random randomNumber = new Random();
int x = randomNumber.Next(1, 6);
switch (x)
{
case 1:
//imgDie.ImageUrl = "~/Images/dice1.jpg";
Session["Die"] = "~/Images/dice1.jpg";
break;
case 2:
Session["Die"] = "~/Images/dice2.jpg";
break;
case 3:
Session["Die"] = "~/Images/dice3.jpg";
break;
case 4:
Session["Die"] = "~/Images/dice4.jpg";
break;
case 5:
Session["Die"] = "~/Images/dice5.jpg";
break;
case 6:
Session["Die"] = "~/Images/dice6.jpg";
break;
}
imgDie.ImageUrl = (string)Session["Die"];
place = place + x;
switch (place)
{
case 2:
img2.Visible = true;
img2.ImageUrl = (string)Session["Imagesrc"];
break;
case 3:
img3.Visible = true;
img3.ImageUrl = (string)Session["Imagesrc"];
break;
case 4:
img4.Visible = true;
img4.ImageUrl = (string)Session["Imagesrc"];
break;
case 5:
img5.Visible = true;
img5.ImageUrl = (string)Session["Imagesrc"];
break;
case 6:
img6.Visible = true;
img6.ImageUrl = (string)Session["Imagesrc"];
break;
case 7:
img7.Visible = true;
img7.ImageUrl = (string)Session["Imagesrc"];
break;
case 8:
img8.ImageUrl = (string)Session["Imagesrc"];
img8.Visible = true;
break;
my guess is your 'place' variable is a member field and it's being reinitialized with each page construction. chnge your place variable to be viewstate or session state like your other stuff.
How does one go about finding the month name in C#? I don't want to write a huge switch statement or if statement on the month int. In VB.Net you can use MonthName(), but what about C#?
You can use the CultureInfo to get the month name. You can even get the short month name as well as other fun things.
I would suggestion you put these into extension methods, which will allow you to write less code later. However you can implement however you like.
Here is an example of how to do it using extension methods:
using System;
using System.Globalization;
class Program
{
static void Main()
{
Console.WriteLine(DateTime.Now.ToMonthName());
Console.WriteLine(DateTime.Now.ToShortMonthName());
Console.Read();
}
}
static class DateTimeExtensions
{
public static string ToMonthName(this DateTime dateTime)
{
return CultureInfo.CurrentCulture.DateTimeFormat.GetMonthName(dateTime.Month);
}
public static string ToShortMonthName(this DateTime dateTime)
{
return CultureInfo.CurrentCulture.DateTimeFormat.GetAbbreviatedMonthName(dateTime.Month);
}
}
Hope this helps!
Use the "MMMM" format specifier:
string month = dateTime.ToString("MMMM");
string CurrentMonth = String.Format("{0:MMMM}", DateTime.Now)
Supposing your date is today. Hope this helps you.
DateTime dt = DateTime.Today;
string thisMonth= dt.ToString("MMMM");
Console.WriteLine(thisMonth);
If you just want to use MonthName then reference Microsoft.VisualBasic and it's in Microsoft.VisualBasic.DateAndTime
//eg. Get January
String monthName = Microsoft.VisualBasic.DateAndTime.MonthName(1);
private string MonthName(int m)
{
string res;
switch (m)
{
case 1:
res="Ene";
break;
case 2:
res = "Feb";
break;
case 3:
res = "Mar";
break;
case 4:
res = "Abr";
break;
case 5:
res = "May";
break;
case 6:
res = "Jun";
break;
case 7:
res = "Jul";
break;
case 8:
res = "Ago";
break;
case 9:
res = "Sep";
break;
case 10:
res = "Oct";
break;
case 11:
res = "Nov";
break;
case 12:
res = "Dic";
break;
default:
res = "Nulo";
break;
}
return res;
}