Search code examples
c#computer-sciencelocalref

Giving a local method a referenced argument


I am passing a ref var to a method, and within the method I have a local method I'd like to ref the var that I passed to the initial method. Example below

private void SomeMethod(ref var refdVar, var someThing)
{
    //do something
    //then call the method below
    LocalMethod(refdVar);
    
   void LocalMethod(ref var refdVar)
   {
       refdVar = someThing;
   }
}

Is this possible to do, if not, what are the options (I don't want to globally change the var, just because I find it cleaner by changing ref)?


Solution

  • I am not completely sure what you are trying to do but maybe a generic method could be what you are looking for : https://learn.microsoft.com/en-us/dotnet/csharp/programming-guide/generics/generic-methods

    private void SomeMethod<T>(ref T refdVar, T someThing)
    {
      //do something
      //then call the method below
      LocalMethod(ref refdVar);
    
      void LocalMethod(ref T refdVar1)
      {
        refdVar1 = someThing;
      }
    }
    ....
    ....
    int x = 3;
    SomeMethod(ref x, 4);
    double y = 5.0;
    SomeMethod(ref y, 7.0);
    

    Also note that the parameter refdVar is in scope inside the local parameter, so you should give that parameter a different name to avoid a compiler warning.