Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
129 views
in Technique[技术] by (71.8m points)

c# - Out parameters and exceptions

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)

question from:https://stackoverflow.com/questions/8906842/out-parameters-and-exceptions

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...