1

As below code expressed, I want SomeMethod

  • Have a parameter of some kind of int
  • can accept null as parameter
  • if parameter is none null, it will use it's value, then update the value of argument variable in Caller2

    void Caller1()
    {
        SomeMethod(null, ...);
    }
    
    void Caller2()
    {
        int argument = 123;
        SomeMethod(argument, ...);
        Debug.Assert(argument == 456);
    }
    
    void SomeMethod(SomeKindOfInt parameter, ...)
    {
        if (parameter != null)
        {
            // use the value of parameter;
            parameter = 456; // update the value of argument which is in Caller2
        }
    }
    

Tried and declare:

  • ref int can't accept null
  • int? can't update argument in caller
  • Create a custom Wrapper class of int did this, but is there a light way or does C# or .net have some build in tech?
  • It's not good to split it into two methods because there's a big logic inside which is common whenever parameter is null or none null.
Ori Nachum
  • 588
  • 3
  • 19
Fengtao Ding
  • 706
  • 8
  • 17

1 Answers1

2

Almost there, you can use int? to allow null value and put the ref keyword.

static void Main(string[] args)
{
    int? test1 = null;
    SomeMethod(ref test1);
    Console.WriteLine(test1);
    // Display 456

    int? test2 = 123;
    SomeMethod(ref test2);
    Console.WriteLine(test2);
    // Display 123

    Console.ReadLine();
}

static void SomeMethod(ref int? parameter)
{
    if (parameter == null)
    {
        parameter = 456;
    }
}
dbraillon
  • 1,742
  • 2
  • 22
  • 34
  • Thank you, ref int? can do this but it doesn't accept literal SomeMethod(null, ..) , it need to call like this: int? unused = null; SomeMethod(ref unused). In my individual case, I prefer Jehof's solution. Thank you anyway. – Fengtao Ding Mar 06 '17 at 08:05