0

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;
        }

enter image description here

5 Answers 5

3

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;
Sign up to request clarification or add additional context in comments.

Comments

2

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.

Comments

2

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;

Comments

1

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;
    }
}

Comments

0

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;
    }
}

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.