Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

One method accepting different parameters

Tags:

c#

.net

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?

like image 822
Itay.B Avatar asked Nov 27 '22 01:11

Itay.B


2 Answers

Three options for you to consider, depending on what you're actually trying to achieve:

Use overloads

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.

Use object

public void DoSomething(object s) { ... }

This will allow you to pass in anything.

Use generics

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)

like image 160
Jon Skeet Avatar answered Dec 29 '22 01:12

Jon Skeet


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()); }
like image 39
juunas Avatar answered Dec 29 '22 00:12

juunas