-2

I have a method that I want to send several parameters or one or none

public void CalcBreakpoint(int tolerance, [I want to send several parameters or one or none])
{
//my code
}

for example something I want to call it as CalcBreakpoint(200, "string value1", "string value 2", "String Value 3")

and in other occasions I would call it as CalcBreakpoint(500, object1, object2)

I would like to avoid overloading because 90% of the code is the same.

How to pass several values as parameters in a method? such as

public void CalcBreakpoint(int tolerance, [ONE_PARAMETER])

Victor A Chavez
  • 181
  • 1
  • 19

2 Answers2

4

if they will always be strings you can do:

public void void CalcBreakpoint(int tolerance, params string[] args)
{
    //my code
}

if they are set parameters you use:

public void params void CalcBreakpoint(int tolerance, string arg1 = null, int? arg2 = null, object arg3 = null, decimal? arg4 = null)
{
    //my code
}

The second one gives you an advantage of being able to call it like so:

CalcBreakpoint(34, arg3: "asdf");
maraaaaaaaa
  • 7,749
  • 2
  • 22
  • 37
0

In addition to maksymiuk's excellent suggestions, I'd like to point out that you could also do one of the following:

// If you're using "mixed types"
public void CalcBreakpoint(int tolerance, params object[] args)
{
   //...
}

// The use of dynamic here is controversial but it can accomplish something similar to the above code sample
public void void CalcBreakpoint(int tolerance, params dynamic[] args)
{
    //....
}

// If all of the arguments are of the same type but you don't know "in advance"
// what that type will be, you can use generics here
public void CalcBreakpoint<T>(int tolerance, params T[] args)
{
    //my code
}