I need to translate/rewrite some C++ code in C#. For quite a few methods, the person who wrote the C++ code had done something like this in the prototype,
float method(float a, float b, int *x = NULL);
And then in the method something like this,
float method(float a, float b, int *x) {
float somethingElse = 0;
int y = 0;
//something happens here
//then some arithmetic operation happens to y here
if (x != NULL) *x = y;
return somethingElse;
}
I've confirmed that x is an optional parameter for the method, but now I'm having trouble rewriting this in C#. Unless I use pointers and dip unsafe mode I'm not really sure how to do this since int cannot be null.
I have tried something like this,
public class Test
{
public static int test(ref int? n)
{
int x = 10;
n = 5;
if (n != null) {
Console.WriteLine("not null");
n = x;
return 0;
}
Console.WriteLine("is null");
return 1;
}
public static void Main()
{
int? i = null;
//int j = 100;
test(ref i);
//test(ref j);
Console.WriteLine(i);
}
}
If I uncomment the lines with the variable j in the main() method, the code does not compile and says that the type int does not match the type int?. But either way, these methods will be used later and int will be passed into them, so I'm not really keen on using the int? to maintain compatibility.
I have looked into optional arguments in C#, but that still doesn't mean I can use null as a default value for int, and I do not know which values this variable won't encounter.
I have also looked into the ?? null-coalescing operator, but this seems to be the reverse of what I'm trying to do.
Could I get some advice on what I should do please?
Thanks in advance.
It looks to me like you want an optional out parameter.
I would do it with overrides in C#.
public static float method(float a, float b, out int x){
//Implementation
}
public static float method(float a, float b){
//Helper
int x;
return method(a, b, out x);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With