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

后端 未结 8 828
逝去的感伤
逝去的感伤 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: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:

    /// 
    /// Example code for how  might be implemented.
    /// 
    /// A string to convert to an integer.
    /// The result of the parse if the operation was successful.
    /// true if the  parameter was successfully 
    /// parsed into the  integer; false otherwise.
    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 mDictionary = new Dictionary();
    
    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.

提交回复
热议问题