Skip to content

Instantly share code, notes, and snippets.

@binki
Created November 27, 2017 15:03
Show Gist options
  • Save binki/9ad9f3c4fa2b0346b507d113894e6ce5 to your computer and use it in GitHub Desktop.
Save binki/9ad9f3c4fa2b0346b507d113894e6ce5 to your computer and use it in GitHub Desktop.
csharp out parameters and exceptions
using System;
class Program
{
static void Main(string[] args)
{
var x = 5;
try
{
MethodThrowBeforeWrite(out x);
}
catch
{
}
// x=5
Console.WriteLine($"x={x}");
try
{
MethodThrowAfterWrite(out x);
}
catch
{
}
// x=2
Console.WriteLine($"x={x}");
}
static void MethodThrowBeforeWrite(out int x)
{
throw new InvalidOperationException();
}
static void MethodThrowAfterWrite(out int x)
{
x = 2;
throw new InvalidOperationException();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment