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 am trying to think of a scenerio when I would use it.
Can someone give me a real-world example? Thanks.
or something similar like Dictionary.TryGetValue.
But I would consider this one to be a not too good practice to employ it, of course, using those provided by API like the Int32 one to avoid Try-Catch is exceptions.
Sure, take a look at any of the
TryParse
methods, such asint.TryParse
:The idea is you actually want two pieces of information: whether a parse operation was successful (the return value), and, if so, what the result of it actually was (the
out
parameter).Usage:
Many developers complain of
out
parameters as a "code smell"; but they can be by far the most appropriate choice in many scenarios. One very important modern example would be multithreaded code; often anout
parameter is necessary to permit "atomic" operations where a return value would not suffice.Consider for example
Monitor.TryEnter(object, ref bool)
, which acquires a lock and sets abool
atomically, something that wouldn't be possible via a return value alone since the lock acquisition would necessarily happen before the return value were assigned to abool
variable. (Yes, technicallyref
andout
are not the same; but they're very close).Another good example would be some of the methods available to the collection classes in the
System.Collections.Concurrent
namespace new to .NET 4.0; these provide similarly thread-safe operations such asConcurrentQueue<T>.TryDequeue(out T)
andConcurrentDictionary<TKey, TValue>.TryRemove(TKey, out TValue)
.