I have a method like this:
public void Foo(params string[] args) {
bar(args[0]);
bar(args[1]);
}
The new requirements lead to a change like this:
public void Foo(string baz, params string[] args) {
if("do bar".Equals(baz)) {
bar(args[0]);
bar(args[1]);
}
}
The problem is that even though I've changed the method signature, no compilation errors occur, which is correct of course, but I want there to be compilation errors for every call to Foo
method where the argument baz
has not been specified. That is, if a call to Foo
before the change was this one:
Foo(p1,p2); //where p1 and p2 are strings
it now needs to be this one:
Foo(baz,p1,p2);
If it wouldn't be changed in this way, p1
would be assigned to baz
, and the params array args
would be of length 1 and an OutOfBounds
exception would be thrown.
What's the best way to change the signature and ensure that all the calling code is updated accordingly? (The real scenario is where Foo
lives in an assembly shared by many projects automatically built on a build server. A compilation error would thus be an easy way to detect all the code that needs to be touched to accomodate the change.)
Edit: As Daniel Mann and others pointed out, the example above suggests that I should not use params at all. So I should explain that in my real world example it's not always the case that args needs to have two elements, as far as the logic in Foo is concerned args can contain any number of elements. So let's say this is Foo:
public void Foo(string baz, params string[] args) {
if("do bar".Equals(baz)) {
int x = GetANumberDynamically();
for(int i = 0; i<x; i++)
bar(args[i]);
}
}
int
or something). Then a compile error will be thrown on all the methods? Of course a better way would be to refactor with Resharper or similar. – Dowerint
instead of thestring
, compile, modify all calling code, then change theint
tostring
. Also note thatif("do bar".Equals(baz)) {
is a really bad example, it sounds like another overload or more refactoring is required. – Boyhood