I have method which process the double arrays. I am supplying double arrays using keyword params
. My problem is sometimesI have to pass doubles as well and I want to use to same method for both types. Currently method have signature
public void DoSomething(params double[][] arrays)
Above method definition works fine for following arguments:
double [] array = new double []{2,3,5} ;
double [] anotherarray = new double []{7,8,10} ;
DoSomething (array, anotherarray) ;
I am thing to pass object and then cast them in this method and use try catch block and I do not know it is right approach or there exists some elegant way to handle this kind of situation because I can have mixed data as input arguments.
public void DoSomething(params object objs)
{
// for loop
try
{
var tempdata = (double) objs(loop index);
double[] data = new double[] { tempdata };
}
catch
{
var tempdata = (double []) objs(loop index);
double [] data = tempdata;
}
// do other opertaion
}
I want to call this way:
double [] array = new double []{2,3,5} ;
double singlevalue = 10 ;
double [] anotherarray = new double []{7,8,10} ;
DoSomething (array, singlevalue, anotherarray) ;
Now you've given an example of how you want to call it, I suspect that using dynamic typing may be the simplest approach:
public void DoSomething(params object[] values)
{
foreach (dynamic value in values)
{
// Overload resolution will be performed at execution time
DoSomethingImpl(value);
}
}
private void DoSomethingImpl(double value) { ... }
private void DoSomethingImpl(double[] value) { ... }
You could do it manually if you want:
public void DoSomething(params object[] values)
{
foreach (object value in values)
{
if (value is double)
{
DoSomethingImpl((double) value);
// Or: DoSomethingImpl(new[] { (double) value });
}
else if (value is double[])
{
DoSomethingImpl((double[]) value);
}
...
}
}
I would definitely not just cast unconditionally and then catch the exception that's thrown. That's a horrible abuse of exceptions.
See more on this question at Stackoverflow