Out parameters and exceptions

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 … Read more

When should I use out parameters?

Out is good when you have a TryNNN function and it’s clear that the out-parameter will always be set even if the function does not succeed. This allows you rely on the fact that the local variable you declare will be set rather than having to place checks later in your code against null. (A … Read more

Returning two values, Tuple vs ‘out’ vs ‘struct’

They each have their pros and cons. Out parameters are fast and cheap but require that you pass in a variable, and rely upon mutation. It is almost impossible to correctly use an out parameter with LINQ. Tuples create collection pressure1 and are un-self-documenting. “Item1” is not very descriptive. Custom structs can be slow to … Read more

How to explicitly discard an out argument?

Starting with C# 7.0, it is possible to avoid predeclaring out parameters as well as ignoring them. public void PrintCoordinates(Point p) { p.GetCoordinates(out int x, out int y); WriteLine($”({x}, {y})”); } public void PrintXCoordinate(Point p) { p.GetCoordinates(out int x, out _); // I only care about x WriteLine($”{x}”); } Source: https://blogs.msdn.microsoft.com/dotnet/2017/03/09/new-features-in-c-7-0/

Assigning out/ref parameters in Moq

For ‘out’, the following seems to work for me. public interface IService { void DoSomething(out string a); } [TestMethod] public void Test() { var service = new Mock<IService>(); var expectedValue = “value”; service.Setup(s => s.DoSomething(out expectedValue)); string actualValue; service.Object.DoSomething(out actualValue); Assert.AreEqual(expectedValue, actualValue); } I’m guessing that Moq looks at the value of ‘expectedValue’ when you … Read more