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)
You can achieve what you want with overloads.
void DoSomething(string s){ DoSomething(int.Parse(s)); }
void DoSomething(int s){ /* Your code here */ }
Or the other way around:
void DoSomething(string s){ /* Your code here */ }
void DoSomething(int s){ DoSomething(s.ToString()); }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With