Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Out parameters and exceptions

Tags:

c#

exception

out

Say I have the following code:

    static void Fjuk(out string str)     {         str = "fjuk!";         throw new Exception();     }      static void Main(string[] args)     {         string s = null;         try         {             Fjuk(out s);         }         catch (Exception)         {             Console.WriteLine(s ?? "");         }     } 

When I test it, s has been initialized to "fjuk!" when it's used in the catch block.
Is this guaranteed by specification or is it implementation dependent? (I have searched the C# 3 spec but couldn't find out myself)

like image 718
Niklas Avatar asked Jan 18 '12 07:01

Niklas


People also ask

What are out parameters?

The out parameter in C# is used to pass arguments to methods by reference. It differs from the ref keyword in that it does not require parameter variables to be initialized before they are passed to a method. The out keyword must be explicitly declared in the method's definition​ as well as in the calling method.

What is parameter exception?

Remarks. ArgumentException is thrown when a method is invoked and at least one of the passed arguments does not meet the parameter specification of the called method. The ParamName property identifies the invalid argument.

What is in parameter and out parameter?

It is also similar to the in keyword but the in keyword does not allow the method that called to change the argument value but ref allows. For using out keyword as a parameter both the method definition and calling method must use the out keyword explicitly.

What is an out parameter in Java?

Output parameters. A method may occasionally need to use a parameter for its return value - what might be loosely called an "output parameter" or a "result parameter". The caller creates an output parameter object, and then passes it to a method which changes the state of the object (its data).


1 Answers

Pretty much, that is an aspect of what out means; firstly, note that out doesn't really exist - we only really need to consider ref (out is just ref with some "definite assignment" tweaks at the compiler). ref means "pass the address of this" - if we change the value via the address, then that shows immediately - it is, after all, updating the memory on the stack of Main. It can't abstract this (to delay the write) because the value could be, for example, some oversized struct that is using ref specifically for the purpose of avoiding copying it on the stack (an approach used extensively in XNA etc).

like image 71
Marc Gravell Avatar answered Sep 19 '22 16:09

Marc Gravell