I would do this in one of two ways. If you really want to have a reference to your object, you can wrap this in a class. They are always passed by reference, so you get your modification the way you want, and you can create it for null.
Here is an example.
public class HolderObject { public string myStr {get; set;} } public class Program { public static void Main() { var xyz = new HolderObject() { myStr = "1234" }; Console.WriteLine(xyz.myStr); FixString(xyz); Console.WriteLine(xyz.myStr); FixString(); Console.WriteLine(xyz.myStr); } private static bool FixString(HolderObject input = null) { if (input != null) input.myStr = "test"; return true; } }
prints
1234 test
Another solution is to overload your function.
bool Foo() { // ... return true; } bool Foo(ref int retVal = null) { // ... if (retVal != null) { retVal = 5; } return Foo(); }
I really don't like this. I'm actually in the middle of working on C # code that was pulled directly from C ++. Functions nested in 6 or 7 layers that deeply modify the object that was passed by reference. This is hard to read, and if you look at the code analysis warnings, it will suggest you not to use ref values.
If you can get as far as possible from going through ref and return the value that was changed back. Or pass back an object containing both your bool and your new value.
source share