Reputation: 46591
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.
Upvotes: 2
Views: 609
Reputation: 41236
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.
var myObj = SetObjectAccordingTo(c);
protected SomeObj SetObjectAccordingTo(string c)
{
var myObj = new SomeObj();
switch(c)
{
case "1": myObj.a = 1;
break;
case "2": myObj.b = 2;
break;
}
return myObj;
}
If they are not logically grouped, and each is assigned a value...
Then logic for determining each value needs to be split.
a = DetermineValueForA(c);
b = DetermineValueForB(c);
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.
Upvotes: 2
Reputation: 9367
You mean you'd like to extract this as a method? You might consider returning a struct (or perhaps a class) if A and B are related in some manner. Perhaps, NDA permitting, you could show us a code fragment in context so it might become clearer how to solve this.
Upvotes: 1