Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get a value through a out/ref parameter from a method which throws an exception?

this code outputs "out value".

class P
{
  public static void Main()
  {
    string arg = null;
    try
    {
      Method(out arg);
    }
    catch
    {
    }
    Console.WriteLine(arg);
  }
  public static void Method(out string arg)
  {
    arg = "out value";
    throw new Exception();
  }
}

but this one doesn't.

class P
{
  public static void Main()
  {
    object[] args = new object[1];
    MethodInfo mi = typeof(P).GetMethod("Method");
    try
    {
      mi.Invoke(null, args);
    }
    catch
    {
    }
    Console.WriteLine(args[0]);
  }
  public static void Method(out string arg)
  {
    arg = "out value";
    throw new Exception();
  }
}

how can I get both "out value" and an exception when using reflection?

like image 501
matarillo Avatar asked Jan 20 '10 10:01

matarillo


1 Answers

The exception bypassed the code in MethodInfo.Invoke() that copies the [out] value from the stack frame back into the object array. The value on the stack frame that Invoke() created behaves just like it does in your 1st snippet. But that's where the similarities end.

like image 171
Hans Passant Avatar answered Oct 04 '22 12:10

Hans Passant