How can I refactor a switch statement that is in multiple places in code that assigns a value to a variable depending on which case is thrown, for example:
int a = 0;
int b = 0;
switch(c)
{
case "1"
a = 1;
break;
case "2"
b = 2;
break;
}
In the above example, resharper will use one of the variables as the return and the other as an out parameter. Is there another way to do it, maybe not extracting out the whole switch block.
This code block has a couple of different ways of refactoring it to make it more reusable without having it copied over in places. However, they’re going to require reworks of things:
Are the objects logically grouped somehow?
If so, then you could make an object to represent them, and then refactor to return the object set with values.
If they are not logically grouped, and each is assigned a value…
Then logic for determining each value needs to be split.
And each method deals only with the cases where a is involved.
If they are not logically grouped, and only certain values are assigned…
Then there is not much optimization that can be performed save moving the respective values to member variables and then calling each with that specific method.
If you could provide a sample of what you’re trying to do, we could offer a solution more than likely.