Created
May 11, 2023 04:48
-
-
Save BinToss/e6b69b9688906730edab85a5c5109c46 to your computer and use it in GitHub Desktop.
C# - Using nullable values, can a property's backing field initialize only when needed?
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!meta | |
{"kernelInfo":{"defaultKernelName":"csharp","items":[{"aliases":[],"name":"csharp"}]}} | |
#!csharp | |
/** Q: C# - Using nullable values, can a property's backing field initialize only when needed? | |
A: If null or default initialization is acceptable, yes. Until get_Property is called, the field's value will remain default. (null, null) in this example. | |
*/ | |
using System.ComponentModel; | |
#nullable enable | |
//default((bool?, Exception?)).Display(); // (null, null) | |
//((bool?)true, (Exception?)null).Display(); // (true, null) | |
public class TestClass | |
{ | |
private (bool? v, Exception? ex) testProperty; | |
public (bool? v, Exception? ex) TestProperty{ | |
get{ | |
if (testProperty is (null, null)) // constant instead of default to use 'is' | |
{ | |
testProperty.Display(); | |
/** (, ) | |
Item1 <null> | |
Item2 <null> | |
*/ | |
return testProperty = (true, null); | |
} | |
else | |
{ | |
return testProperty; | |
} | |
} | |
} | |
} | |
var t = new TestClass(); | |
t.TestProperty.v.Display(); // True |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment