I have a method that I’m writing that is calling another overloaded method inside it. I’d like to only write one outer method, since the parameter to the outer method is being passed to the inner one. Is there a way to do this?
I tried using generics, but I don’t know enough about this so it isn’t working:
public void OuterMethod<T>(T parameter) { InnerMethod(parameter); // InnerMethod accepts an int or a string }
I know that I can do this:
public void OuterMethod(string parameter) { InnerMethod(parameter); } public void OuterMethod(int parameter) { InnerMethod(parameter); }
But I’d rather do this the right way instead of copying/pasting code. What’s the best way to accomplish this?
You can do this in C++ but not in C# (unless the inner method can also be generic instead of overloaded).
Alternatively (if you won’t take ‘no’ for an answer), you can do a run-time switch on type, like for example …
… but obviously this is a run-time, not a compile-time check.
You can also write software to write your outer methods (e.g. using System.CodeDom classes) instead of writing them by hand, but this is probably more trouble than it’s worth.