title: C++ null pointer argument as optional argument alternative in C#
body: <p>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,</p>
  
  <pre><code>float method(float a, float b, int *x = NULL);
  </code></pre>
  
  <p>And then in the method something like this,</p>
  
  <pre><code>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;
  
  }
  </code></pre>
  
  <p>I've confirmed that <code>x</code> 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 <code>int</code> cannot be <code>null</code>. </p>
  
  <p>I have tried something like this,</p>
  
  <pre><code>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);
      }
  }
  </code></pre>
  
  <p>If I uncomment the lines with the variable <code>j</code> in the <code>main()</code> method, the code does not compile and says that the type <code>int</code> does not match the type <code>int?</code>. But either way, these methods will be used later and <code>int</code> will be passed into them, so I'm not really keen on using the <code>int?</code> to maintain compatibility.</p>
  
  <p>I have looked into optional arguments in C#, but that still doesn't mean I can use <code>null</code> as a default value for <code>int</code>, and I do not know which values this variable won't encounter.</p>
  
  <p>I have also looked into the <code>??</code> null-coalescing operator, but this seems to be the reverse of what I'm trying to do.</p>
  
  <p>Could I get some advice on what I should do please?</p>
  
  <p>Thanks in advance.</p>