Using FW 4.5.1
I have a method:
void DoSomething(string s)
I want to allow the function to accept int
as well, but under the same parameter s. That means I want to write:
void DoSomething(var s)
and sometimes s
will be int
, sometimes string
.
How can I achieve this?
Three options for you to consider, depending on what you're actually trying to achieve:
public void DoSomething(int s) { ... }
public void DoSomething(string s) { ... }
This will only accept int
and string
- which could be a good or a bad thing, depending on what you're trying to achieve. If you really only want to be able to accept int
and string
, this is the best solution IMO.
object
public void DoSomething(object s) { ... }
This will allow you to pass in anything.
public void DoSomething<T>(T value) { ... }
This will still allow you to pass in anything, but will provide a bit more type safety if (say) you want to later accept two values which have to be the same type (or at least compatible types)
See more on this question at Stackoverflow