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;
}
}
Related
Of course before posting this error I searched the heck out it. The code below returns: error CS0029: Cannot implicitly convert type 'bool' to 'string' in two spots. Am I misunderstanding why the code below isn't returning a string? Thinking to myself what advice Stack Overflow might give I've tried my best to explicitly cast to a string but have only managed to confuse myself.
public static class Bob
{
public static string Response(string statement)
{
string teststring = statement;
bool IsAllUpper(string input)
{
for (int i = 0; i < input.Length; i++)
{
if (Char.IsLetter(input[i]) && !Char.IsUpper(input[i]))
return false;
}
return true;
}
switch(teststring)
{
case IsAllUpper(teststring) && teststring.EndsWith("?"):
string final1 = "Calm down, I know what I'm doing!";
return final1;
case teststring.EndsWith("?"):
string final2 = "Sure";
return final2;
default:
string final3 = "Whatever.";
return final3;
}
}
public static void Main()
{
string input = "This is the end";
Console.WriteLine("{0}", Response(input));
}
}
With switch(teststring) you're asking the code to switch on string values, e.g. "foo" and "bar". However, your cases are boolean values: IsAllUpper(teststring) and teststring.EndsWith("?") both return booleans.
Consider replacing the switch block with if statements, something like
if (IsAllUpper(teststring) && teststring.EndsWith("?")) {
string final1 = "Calm down, I know what I'm doing!";
return final1;
}
if (teststring.EndsWith("?")) {
string final2 = "Sure";
return final2;
}
string final3 = "Whatever.";
return final3;
or, for maximum conciseness obscurity, the one-liner:
return teststring.EndsWith("?") ? (IsAllUpper(teststring) ? "Calm down, I know what I'm doing!" : "Sure") : "Whatever."
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.
I am creating a C# Console app which is Replacing a Hyphen for Zeros to complete the maximum length of my String from an identification card "123456-72"and I am facing a hard time when have to sort in my array.
I would like sort the first digit or character from this "123456-72" as well in some cases I need to sort from the first two digit "391234-56".
This example is working fine, but only for first character. I need to
Example:
class IdentificationNumber {
private string IDNumber;
private int Customertype;
private string check;
private string pad;
private string longFormat;
SortedList GroupID = new SortedList();
public IdentificationNumber(string IDNumber) {
this.IDNumber= IDNumber;
}
public string getLongFormat() {
var ReplaceHyp = IDNumber.Replace("-", "");
int Customertype= Int32.Parse(IDNumber.Substring(0,2));
//Array
//GroupID .Add(1,"Blue");
//GroupID .Add(2,"Blue");
GroupID .Add(38,"White");
GroupID .Add(39,"Blue");
pad="";
check = GroupID.GetByIndex(GroupID.IndexOfKey(Customertype)).ToString();
Console.WriteLine(Customertype);
Console.WriteLine(check);
switch (check) {
case("White"):
longFormat= ReplaceHyp.Substring(0,6)+pad.PadLeft((14 -ReplaceHyp.Length),'0')+ReplaceHyp.Substring(6,(ReplaceHyp.Length-6));
break;
case("Blue"):
longFormat= ReplaceHyp.Substring(0,7)+pad.PadLeft((14 -ReplaceHyp.Length),'0')+ReplaceHyp.Substring(7,(ReplaceHyp.Length-7));
break;
}
return longFormat;
}
}
Any solution or suggestion?
Here is a skeleton of the comparator method you might need:
public static int CompareStrings(string s1, string s2)
{
int Customertype1 = Int32.Parse(s1.Substring(0,2));
int Customertype2 = Int32.Parse(s2.Substring(0,2));
string check1 = GroupID.GetByIndex(GroupID.IndexOfKey(Customertype1)).ToString();
string check2 = GroupID.GetByIndex(GroupID.IndexOfKey(Customertype2)).ToString();
if (Customertype1 > Customertype2)
return 1;
if (Customertype1 < Customertype2)
return -1;
else
{
var ReplaceHyp1 = s1.Replace("-", "");
switch (check1) {
case("White"):
longFormat1 = ReplaceHyp1.Substring(0,6)+pad.PadLeft((14 -ReplaceHyp1.Length),'0')+ReplaceHyp1.Substring(6,(ReplaceHyp1.Length-6));
break;
case("Blue"):
longFormat1 = ReplaceHyp1.Substring(0,7)+pad.PadLeft((14 -ReplaceHyp1.Length),'0')+ReplaceHyp1.Substring(7,(ReplaceHyp1.Length-7));
break;
}
var ReplaceHyp2 = s2.Replace("-", "");
switch (check2) {
case("White"):
longFormat2 = ReplaceHyp2.Substring(0,6)+pad.PadLeft((14 -ReplaceHyp2.Length),'0')+ReplaceHyp2.Substring(6,(ReplaceHyp2.Length-6));
break;
case("Blue"):
longFormat2 = ReplaceHyp2.Substring(0,7)+pad.PadLeft((14 -ReplaceHyp2.Length),'0')+ReplaceHyp2.Substring(7,(ReplaceHyp2.Length-7));
break;
}
return stringCompare(longFormat1, longFormat2);
}
}
This code badly needs to be refactored! Depending on your exact needs, I think that the checks of Customertype1/2 can be removed.
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";
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;
}
}