Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save BinToss/e6b69b9688906730edab85a5c5109c46 to your computer and use it in GitHub Desktop.
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?
#!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