How to typecast single element of List<double> as type 'double' in calculation in C#

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?

Jon Skeet
people
quotationmark

There are four problems here:

  • You have to use ref on the argument as well as the parameter
  • The expression o[i] - offset is classified as a value rather than a variable, so you can't pass it by reference
  • Even the expression o[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.
  • You're trying to use the result of a 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);
}

people

See more on this question at Stackoverflow