I have multiple functions from which i output last errors.
In c++, you can just pass a nullptr default initializer in the function prototype and it compiles fine, but in C# it doesn't seem to allow you to initialize out
or ref
parameters in case you do not need to use them.
There are of course plenty of answers to my question, such as just storing them within the class and such, but for my purposes, passing it from the function itself would be the prefered way.
So is there any way to have an out
or ref
-like parameter to a function and be able to initialize it to default values in case the user does not want to use it?
Perhaps you can use the c++ syntax somehow? (the pointers and byrefs, maybe using unsafe code?)
It might be a little tedious, but you could have an out-error-less overload for each function:
using System;
class MainClass {
public static int DoThing(int a, int b, out string error) {
error = null;
if(a > 0 && b > 0) return a * b;
error = "Both arguments need to be > 0, so I'm just returning zero";
return 0;
}
public static int DoThing(int a, int b) {
return DoThing(a, b, out _);
}
public static void Main (string[] args) {
Console.WriteLine(DoThing(3, 6).ToString());
}
}
(Or you could consider a generic return type that wraps the actual returned value and any errors that occur along the way, maybe.)