Real-world examples where C# 'out' parameters are useful?

后端 未结 8 830
逝去的感伤
逝去的感伤 2020-12-29 06:46

I\'m reading up on core C# programming constructs and having a hard time wrapping my head around the out parameter modifier. I know what it does by reading but

相关标签:
8条回答
  • 2020-12-29 07:21

    Simple, when you have a method that returns more than one value. One of the most "famous" cases is Dictionary.TryGetValue:

    string value = "";
    
    if (openWith.TryGetValue("tif", out value))
    {
        Console.WriteLine("For key = \"tif\", value = {0}.", value);
    }
    else
    {
        Console.WriteLine("Key = \"tif\" is not found.");
    }
    
    0 讨论(0)
  • 2020-12-29 07:23

    As others have said - out parameters allow us to return more than one value from a method call without having to wrap the results in struct/class.

    The addition of the xxx.TryParse methods greatly simplified the coding necessary to convert between a string value (frequently from the UI) and a primitive type.

    An example of what you might have had to write to achieve the same functionality is here:

    /// <summary>
    /// Example code for how <see cref="int.TryParse(string,out int)"/> might be implemented.
    /// </summary>
    /// <param name="integerString">A string to convert to an integer.</param>
    /// <param name="result">The result of the parse if the operation was successful.</param>
    /// <returns>true if the <paramref name="integerString"/> parameter was successfully 
    /// parsed into the <paramref name="result"/> integer; false otherwise.</returns>
    public bool TryParse(string integerString, out int result)
    {
        try
        {
            result = int.Parse(integerString);
            return true;
        }
        catch (OverflowException)
        {
            // Handle a number that was correctly formatted but 
            // too large to fit into an Int32.
        }
        catch (FormatException)
        {
            // Handle a number that was incorrectly formatted 
            // and so could not be converted to an Int32.
        }
    
        result = 0; // Default.
        return false;
    }
    

    The two exception checks that are avoided here make the calling code much more readable. I believe that the actual .NET implementations avoid the exceptions altogether so perform better as well. Similarly, this example shows how IDictionary.TryGetValue(...) makes code simpler and more efficient:

    private readonly IDictionary<string,int> mDictionary = new Dictionary<string, int>();
    
    public void IncrementCounter(string counterKey)
    {
        if(mDictionary.ContainsKey(counterKey))
        {
            int existingCount = mDictionary[counterKey];
    
            mDictionary[counterKey] = existingCount + 1;
        }
        else
        {
            mDictionary.Add(counterKey, 1);
        }
    }
    
    public void TryIncrementCounter(string counterKey)
    {
        int existingCount;
        if (mDictionary.TryGetValue(counterKey, out existingCount))
        {
            mDictionary[counterKey] = existingCount + 1;
        }
        else
        {
            mDictionary.Add(counterKey, 1);
        }
    }
    

    And all thanks to the out parameter.

    0 讨论(0)
提交回复
热议问题