I’ve a following method “Test” which accepts a params list:
Public void method Test(params double[] list]
{
Vols vol= new Vols();
//Fill the object based on the input list and
//pass this vol to other private method for further processing
}
Inside this method, am using a custom business object called Vols defined as follows:
public class Vols
{
private double _vol09;
private double _vol05;
private double _vol01;
public Vols()
{
}
public double Vol09
{
get { return _vol09; }
set { _vol09 = value; }
}
public double Vol01
{
get { return _vol01; }
set { _vol01 = value; }
}
public double Vol05
{
get { return _vol05; }
set { _vol05 = value; }
}
}
The user of method “test” can pass in values as: test(0.1,0.9);
So, depending on the input passed, I want to set only the corresponding property in the business object “Vols”….ie. in this case , properties Vol01 and Vol09 would be set in the method “test”.
Is there any way to do this so that I can avoid a switch case inside the method?
This would be possible using reflection…but since reflection is expensive, is there any other approach I can make use of?Also, shall I use switch-case statement or reflection here wrt good coding practices?
Thanks.
It would be more readable if you used an object initializer…
Your constructor can construct the default business object and your property setters can call the corresponding property on Vols.
It also might make sense to use a fluent interface which is always a good choice when there is complex, variable, constructor setup…
or, just inject the business object…
And in C# 4.0, you can use named parameters, all the cool kids are doing it…
Reflection is overkill, and I wouldn’t be worrying about performance. I would be worrying if my test cases clearly revealed intent.