Skip to content

Instantly share code, notes, and snippets.

@emoacht
Created November 10, 2023 05:26
Show Gist options
  • Save emoacht/fca36c31524afc1417320ba3d6adf15c to your computer and use it in GitHub Desktop.
Save emoacht/fca36c31524afc1417320ba3d6adf15c to your computer and use it in GitHub Desktop.
Test null check of property of Property pattern
public static class PropertyPatternTest
{
public static void Test()
{
var t = new TestClass();
// Case 1: False
TestBase(() => t is { Data: { Length: > 0 } });
// Case 2: False
TestBase(() => t is { Data.Length: > 0 });
// Case 3: System.NullReferenceException
TestBase(() => (t is not null) && (t.Data.Length > 0));
// Case 4: False
TestBase(() => (t is not null) && (t.Data?.Length > 0));
static void TestBase(Func<bool> func)
{
try
{
Trace.WriteLine(func.Invoke());
}
catch (Exception ex)
{
Trace.WriteLine(ex);
}
}
}
public class TestClass
{
public int[]? Data { get; init; }
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment