-1

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)?

maxkcy
  • 1
  • 2
  • 1
    This isn't even valid C# to begin with. – aybe Feb 11 '22 at 10:52
  • You can't specify `var` in parameter declarations, and that has nothing to do with `ref`. Do you have a specific type in mind? Or do you want a generic method? If you, as an example, switch the type to `int`, and also use `ref` when calling the local method, it will compile. Can you explain what the problem is? – Lasse V. Karlsen Feb 11 '22 at 11:18
  • To answer your question: Yes, it is possible to do. – Lasse V. Karlsen Feb 11 '22 at 11:22

1 Answers1

1

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.

PaulF
  • 6,673
  • 2
  • 18
  • 29