Switch-case and out parameter in C# - c#

string returnString;
switch(Type) {
case 0: returnString = exampleFunction(foo0, out int exitCode); break;
case 1: returnString = exampleFunction(foo1, out int exitCode); break;
case 2: returnString = exampleFunction(foo2, out int exitCode); break;
}
When I write this code, VS displayed me an error that 'A local variable named or function named 'exitCode' is already defined in this scope' for line 4 and 5. So if I want to get more than two variables with different types from exampleFunction, what should I do? If I can't use out in the code, should I use tuple to get returnString and exitCode from the function?

You could declare exitCode variable before the switch. You should initialize it with some value or have default branch in you switch. Otherwise there is a flow by which exitCode will be uninitialized after the switch. Compiler will not pass this. Also don't forget a break after each case:
int exitCode = 0;
string returnString;
switch(Type) {
case 0: returnString = exampleFunction(foo0, out exitCode); break;
case 1: returnString = exampleFunction(foo1, out exitCode); break;
case 2: returnString = exampleFunction(foo2, out exitCode); break;
}
But overall having a method returning two different values (one as return value and second as out parameter) is a bad practice. Consider having some simple class with those values as properties:
class SomeValue
{
public string Foo { get; set; }
public int Code { get; set; }
}
static SomeValue ExampleFunction(string input)
{
return new SomeValue
{
Foo = input,
Code = 1,
};
}
static void Main(string[] args)
{
// ...
SomeValue val = null;
switch (Type)
{
case 0: val = ExampleFunction(foo0); break;
case 1: val = ExampleFunction(foo1); break;
case 2: val = ExampleFunction(foo2); break;
}
}

Instead of declaring foo0, foo1, and foo2, perhaps you should consider using an array, e.g. foo[]. This is usually a good idea whenever you see variable names with ascending numbers like that.
If you do it that way, the problem goes away, and you code is much shorter:
var returnString = exampleFunction(foo[Type], out int exitCode);
If it doesn't make sense within the problem domain for foo0, foo1, and foo2 to live in an array (e.g. their individual names are important), you can still use a temporary array as a map:
var returnString = exampleFunction(
new[] {foo0, foo1, foo2} [Type],
out int exitCode
);

You should declare "exitCode" only for the first time
case 0: returnString = exampleFunction(foo0, out int exitCode); break;
case 1: returnString = exampleFunction(foo1, out exitCode); break;
case 2: returnString = exampleFunction(foo2, out exitCode); break;
Once you declare it "inline", it becomes local variable for that block.

Related

Couldn't print random switch cases string inside a for loop

Hit everyone! I'm still learning C# and I would like to print different string for each loop based on the switch cases.
static Random rand = new Random();
static void Main(string[] args){
string someString = "";
int someRandom = rand.Next(4);
switch(someRandom) {
case 0:
someString = "Woa";
break;
case 1:
someString = "Waa";
break;
case 2:
someString = "Wee";
break;
case 3:
someString = "Wow!";
break;
}
int someCount = 5;
for (int someInt = 0; someInt < someCount; someInt++) {
Console.WriteLine(someString);
}
Console.Read();
}
What it should do: display random string each loop from the switch.
What it actually does: Selects case randomly and prints the same case in each loop.
I couldn't produce a random string, why is that? I tried adding someRandom = rand.Next(4) inside the for loop but still produces same.
I already tried searching but couldn't find an answer that could solve my problem.
It seems that you are only setting somestring once, and then printing it a bunch. You should put the switch statement in the for loop.
You need to generate the random number (and set the someString variable) inside the loop, otherwise you only pick one random number and then display it multiple times in the loop.
Here's an example but with some slightly better names (IMO):
static Random rand = new Random();
static void Main()
{
int count = 5;
for (int i = 0; i < count; i++)
{
string output;
switch(rand.Next(4))
{
case 0:
output = "Woa";
break;
case 1:
output = "Waa";
break;
case 2:
output = "Wee";
break;
case 3:
output = "Wow!";
break;
default:
output = "This shouldn't happen";
break;
}
Console.WriteLine(output);
}
Console.Read();
}

How from switch to return result return?

How from switch to return result return?
Method1, depending on the value of the variable "str_1", selects an additional method to execute.
I get an error:
"Using local variable" s1 ", which is not assigned a value."
Code
public string Method1(string str_1)
{
string s1;
switch (str_1)
{
case "type_1":
s1 = MethodTest();
break;
}
return s1;
}
public string MethodTest()
{
string s = "test";
return s;
}
Thats correct. Switch not necessarily will lead to use your one case you have.
There are need to be performed one of 2 changes:
1)
string s1 = string.Empty; //(provide default value)
2) provide:
switch (str_1)
{
/*...*/
default:
s1 = "...";
break;
string s1 = string.Empty or string s1 = null
It is complaining that it's possible for that value to not be set since there isn't any guarantee that the switch-case statement will be hit.
s1 has the possibility to have never been set to a value. The error will go away if you while declaring your string, you set it equal to a default value:
string s1 = string.Empty;
I see 4 options:
1) string s1= string.Empty;
2) string s1= null;
3) string s1="";
4) You can make a small refactor:
public string Method1(string str_1)
{
switch (str_1)
{
case "type_1":
return MethodTest();
default:
return string.Empty;
}
}
You can avoid local variable. Just decide what are you going to return in default case.
public string Method1(string str_1)
{
switch (str_1)
{
case "type_1":
return MethodTest();
default:
return null;
}
}

First time using a separate class (.cs) file for a method

Sorry for posting this wall of garbage code :( I didn't want to leave anything out! Im still new and got a little ahead of myself. I wanted to put the "switch case" in a new class so I could reference it faster while also learning to make a new class file. Unfortunately I ran into one bug after another and I couldn't figure out why. The main issue i had is that when I call the case number in the main method, it only returns the string.
Ex. I want the output to be:
"Well [user created name], are you ready to begin your journey to the edge of the world?"
It seems there is an issue with the two classes communicating with eachother.
I have made it worse throwing "public static" at everything to try to make it work. I would really appreciate the help.
using System;
using Test;
public class Scripts
{
public Program p { get; set; }
public void Script(int s)
{
switch (s)
{
case 1:
p.output = "Quest to the edge of the world!";
p.WriteLine();
break;
case 2:
p.output = "Hello! I am your instructor. What is your name apprentice?";
p.WriteLine();
break;
case :
p.output = p.name + " you say? My, what a strange name.";
p.WriteLine();
break;
case 4:
p.output = "Well " + p.name + ", are you ready to begin your journey to the edge of the world?";
p.WriteLine();
break;
case 5:
p.output = " (y)Yes on (n)No";
p.WriteLine();
break;
case 6:
p.output = "OK! Before we go lets go over our gear. What should we prioritize? (1)Magic, (2)Melee, or (3)Ranged?";
p.WriteLine();
break;
case 7:
p.output = "Well I'll just come back tomorrow then.";
p.WriteLine();
break;
case 8:
p.output = "I'm sorry... that's not an option.";
p.WriteLine();
break;
case 9:
p.output = "I'm pretty good at " + p.combatStyle + " combat myself, I'll be sure to teach you everything I know.";
p.WriteLine();
break;
case 10:
p.output = "OK! Let's hit the road and make camp at sundown.";
p.WriteLine();
break;
case 11:
p.output = "Chapter " + p.chapter;
p.WriteLine();
break;
case 12:
p.output = p.name + ", wake up!Were under attack by a couple of goblins!";
p.WriteLine();
break;
case 13:
p.output = "I guess this is the perfect chance to teach you a new" + p.form + "called";
p.WriteLine();
break;
case 14:
p.output = "It makes quick work of their health, but your" + p.energyBar + " will go down just as fast so use it wisely!";
p.WriteLine();
break;
case 15:
p.output = "I'll take care of the one on the right, you engage the one on the left.";
p.WriteLine();
break;
case 16:
p.output = "Press (f) to enter combat. Then press (1) to make an attack";
p.WriteLine();
break;
default:
break;
}
}
}
using System;
using System.Threading;
namespace Test
{
public class Program
{
public Scripts s { get; set; }
// Class Global Variables
public static string input;
public static string output;
public static string name = "bob";
private static string yes = "y";
private static string no = "n";
private static string option1 = "1";
private static string option2 = "2";
private static string option3 = "3";
private static string pathA;
private static string pathB;
private static string pathC;
public static string combatStyle;
private static string weapon;
public static string chapter = "Zero";
public static string form;
public static string energyBar;
private static string healthBar;
Program p = new Program();
public static string[] numbers = new string[] { "One","Two", "Three", "Four", "Five" };
private static int mp = 100;
private static int stamina = 100;
private static int script;
//ReadLine & WriteLine Methods
private static void ReadLine()
{
Console.SetCursorPosition((Console.WindowWidth - 110) / 2, Console.CursorTop);
input = Console.ReadLine();
}
public static void WriteLine()
{
Thread.Sleep(2000);
Console.SetCursorPosition((Console.WindowWidth - output.Length) / 2, Console.CursorTop);
Console.WriteLine(output);
}
//Next Chapter Screen
private static void nextChapter()
{
Thread.Sleep(3000);
Console.Clear();
Thread.Sleep(1500);
output = "\r\n\r\n\r\n\r\n";
WriteLine();
//output = script[12] + chapter;
WriteLine();
Console.Beep();
Thread.Sleep(1500);
Console.Clear();
}
//Yes or No Decision
private static void YesNo()
{
while (input != yes && input != no)
{
ReadLine();
if (input == yes)
{
output = pathA;
WriteLine();
}
else if (input == no)
{
output = pathB;
WriteLine();
}
else
{
//output = script[8];
WriteLine();
}
}
input = "";
}
//Multiple Choice Decision
private static void Choice()
{
while (input != option1 && input != option2 && input != option3)
{
ReadLine();
if (input == option1)
{
output = pathA;
WriteLine();
}
else if (input == option2)
{
output = pathB;
WriteLine();
}
else if (input == option3)
{
output = pathC;
WriteLine();
}
else
{
//output = //script[8];
//WriteLine();
}
}
input = "";
}
//Combat Loop
private static void combatLoop()
{
if (input == "f")
{
}
else
{
//output = script[8];
WriteLine();
combatLoop();
}
}
//Main Method
static void Main()
{
//Chapter Zero "Intro"
Scripts s = new Scripts();
s.Script(1);
s.Script(2);
ReadLine();
name = input;
Console.WriteLine(input);
Console.WriteLine(name);
s.Script(3);
//Chapter One "Combat"
//Chapter Two "Trading"
//Chapter Three "Dungeon"
//Chapter Four "Sailing"
//Chapter Five "The Edge"
// Keep the console open in debug mode.
Console.WriteLine("Press any key to quit game.");
Console.ReadKey();
}
}
}
Looks like your class is in a separate namespace, and the existing namespace for program is not using a using statement for including your separate class.
If you're using static methods / variables, you shouldn't use the object, you should use the class itself:
Program.output = "bla";
Program.WriteLine();
instead of
p.output = "bla";
p.WriteLine();
As your field p isn't even initalized, your current code shouldn't compile. If you want to use the object, you should pass it like that:
public void Script (int s, Program p)
Then you could also make your methods non-static.
Also I'm wondering why you're setting your cursor position to half the length of the text from the right - why not the full offset?
Furthermore you're saying that
The main issue i had is that when I call the case number in the main method, it only returns the string.
What do you mean by returning the string? Your Script method doesn't even have a return type (except for void).

not recognizing a declared variables in c#.net

The last but 3rd line of code is not recognizing variables that I have declared and filled with strings.
static void Main(string[] args)
{
string inputNumber = "1979";
string input1 = inputNumber.Substring(0, 1);
string input2 = inputNumber.Substring(1, 1);
string input3 = inputNumber.Substring(2, 1);
string input4 = inputNumber.Substring(3, 1);
int intInput1;
int intInput2;
int intInput3;
int intInput4;
intInput1 = Convert.ToInt32(input1);
intInput2 = Convert.ToInt32(input2);
intInput3 = Convert.ToInt32(input3);
intInput4 = Convert.ToInt32(input4);
string stringOutput1;
string stringOutput2;
string stringOutput3;
string stringOutput4;
// 1000 Input.
switch (intInput1)
{
case 1:
stringOutput1 = "M";
break;
default:
break;
}
//100 Input
switch (intInput2)
{
case 9:
stringOutput2 = "CM";
break;
default:
break;
}
//10 Input
switch (intInput3)
{
case 7:
stringOutput3 = "LXX";
break;
default:
break;
}
//1 Input
switch (intInput4)
{
case 9:
stringOutput4 = "IX";
break;
default:
break;
}
//Use of unassigned local variable error is showing for 'stringOutput1', 'stringOutput2', 'stringOutput3' and 'stringOutput4'
Console.WriteLine("{0} is {1}{2}{3}{4} in Roman Numerals",inputNumber, stringOutput1, stringOutput2, stringOutput3, stringOutput4);
Console.CursorVisible = false;
Console.ReadKey();
}
P.S. I know that the variables are being filled by commenting out
Console.WriteLine("{0} is {1}{2}{3}{4} in Roman Numerals",inputNumber, stringOutput1, stringOutput2, stringOutput3, stringOutput4);
and using break point and stepping over the code.
This is because your variables might not have been assigned anything yet. Variables must be guaranteed to have been assigned something before they can be used. As a simple fix, you can use declarations like this:
string stringOutput1 = "";
Try assigning nulls to the declarations
string stringOutput1 = null;
string stringOutput2 = null;
string stringOutput3 = null;
string stringOutput4 = null;
You have to initialize your variables, do it like this.
string stringOutput1 , stringOutput1, stringOutput3, stringOutput4 = string.Empty;
and you can also assign default values per variable.
string stringOutput1 = "foo1", stringOutput1 = "foo2"
, stringOutput3= "foo3", stringOutput4 = "foo4";

C# Switch results to list then to comma separated values

How would I make a switch statement populate a list, or comma delimited string?
For example
switch(test)
{
case 0:
"test"
break;
case 1:
"test2"
break;
case 2:
"test3"
break;
}
So my program will go into this statement multiple times. So lets say it goes in there twice and has case 2 and case 1. I woulld like a string value containing the following:
string value = "test3, test2"
Looks like a List<string> would be ideal to hold your values, you can create a comma separated string from that using string.Join():
List<string> myList = new List<string>();
//add items
myList.Add("test2");
//create string from current entries in the list
string myString = string.Join("," myList);
By multiple times, you mean a loop? You can just have a string and concatenate the string using + operator, or you can just have a list and add to it everytime the case condition is satisfied.
But if you mean by conditional flow so that you want case 0, 1 and 2 to all be evaluated, then you can simply omit the break and do the same concatenation like I mentioned above.
private string strValue = string.Empty;
private string StrValue
{
get
{
return strValue ;
}
set
{
StrValue= string.Concat(strValue , ",", value);
}
}
switch(test)
{
case 0:
StrValue = "test"
break;
case1:
StrValue = "test2"
break;
case 2:
StrValue = "test3"
breakl
}
Where ever you used StrValue remove "," if "," comes in the last.
There's a couple ways you can do it, a very simple one is:
string csv = "";
while (yourCriteria) {
string value;
// insert code to get your test value
switch(test)
{
case 0:
value = "test";
break;
case1:
value = "test2";
break;
case 2:
value = "test3";
break;
}
csv += value + ", ";
}
csv = csv.Length > 0 ? csv.Substring(0, csv.Length-2) : "";
Use a loop and a StringBuilder. If you're doing repeated concatenation, StringBuilders are significantly more efficient than naive string concatenation with +.
StringBuilder sb = new StringBuilder();
for(...)
{
switch(test)
{
case 0:
sb.Append("test");
break;
case1:
sb.Append("test2");
break;
case 2:
sb.Append("test3");
break;
}
}

Categories

Resources