In C#, the ?
, when used after a type, indicates that the variable associated with the type can be null or a concrete value. The function you wrote, calcFcl
, has a signature that takes three floats and produces a float as output. However, when you call it, you're providing it with a float?
as the first argument. Since floating-point operations with null values aren't valid, the compiler doesn't know what to do when this is the case.
There are three ways you can address this issue:
- Change
InputCutOffFrequency
so that it is of type float
instead of type float?
.
- Change how you call
calcFc1
so that you send the value of InputCutOffFrequency
instead of the nullable value:
// Force a value (this will throw an InvalidOperationException if `InputCutOffFrequency is null)
fc1 = calcFc1(InputCutOffFrequency.Value, InputFS, InputTransitionBand);
// Coalesce the value (this will force a value, but you need to be sure it's the one you want)
fcl = calcFcl(InputCutOffFrequency ?? 0, InputFS, InputTransitionBand);
- Change the signature of
calcFcl
so that it accepts, for its first argument, a value of float?
and then modify the function body so that it handles the case where the first argument is null.
public float calcFc1(float? f, float fs, float transition)
{
float _f = (f ?? 0) + (transition / 2);
_f /= fs;
return _f;
}
In this case, the f ?? 0
is coalescing f
to a value. Essentially, if f
is null, then 0 will be used. If f
is not null, then the value in f
will be used.
For more information on nullable types in C#, feel free to check out the documentation.