Suppose I have an initialized list: List<double> o
I'd like to perform the following:
int offset = 10;
for (int i = 0; i < o.Count; ++i){
o[i] = ApplyRamp(o[i]-offset)
}
where ApplyRamp is defined as:
public static void ApplyRamp(ref double x)
{
if (x < 0) x = 0;
}
But the code won't compile. Why isn't the single element of a List<double>
, i.e. o[i]
, not treated as type double
?
There are four problems here:
ref
on the argument as well as the parametero[i] - offset
is classified as a value rather than a variable, so you can't pass it by referenceo[i]
would be classified as a value, as it's the result of calling an indexer. If o
were a double[]
(i.e. an array instead of a list) then o[i]
would be classified as a variable.void
method as the right-hand side of an assignment operator. A void
method doesn't have a result.You could use:
double temp = o[i] - offset;
ApplyRamp(ref temp);
// Do something with temp?
But it's not clear what you'd do with temp
afterwards anyway. Are you trying to modify o
? If so, where does offset
come in? And why would you be assigning to o[i]
as well in that case?
Finally, I'd strongly urge you to consider making your ApplyRamp
just use a regular by-value parameter and return the result instead. That will make it easier to use in most cases. I rarely see a good use of ref
parameters in void
methods.
So something like:
public static double ApplyRamp(double x)
{
return x < 0 ? 0 : x;
}
Or just use Math.Max
:
public static double ApplyRamp(double x)
{
return Math.Max(x, 0);
}
See more on this question at Stackoverflow