Created
May 20, 2021 03:43
-
-
Save Adobe-Android/251fb6d1b26819fed2379ae3bff0d11b to your computer and use it in GitHub Desktop.
This file contains hidden or 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
using System; | |
namespace ConsoleApp1 | |
{ | |
class Program | |
{ | |
static void Main(string[] args) | |
{ | |
var getterPropInstance = new GetterAutoProp(); | |
Console.WriteLine(getterPropInstance.RandomInt); | |
Console.WriteLine(getterPropInstance.RandomInt); | |
Console.WriteLine(getterPropInstance.RandomGuid); | |
Console.WriteLine(getterPropInstance.RandomGuid); | |
var autoPropInstance = new LamdbaGetterAutoProp(); | |
Console.WriteLine(autoPropInstance.RandomInt); | |
Console.WriteLine(autoPropInstance.RandomInt); | |
Console.WriteLine(autoPropInstance.RandomGuid); | |
Console.WriteLine(autoPropInstance.RandomGuid); | |
Console.ReadLine(); | |
} | |
} | |
/// <summary> | |
/// Getter-only auto-property | |
/// </summary> | |
public class GetterAutoProp | |
{ | |
/* | |
* Random is implemented as a reference type (class). | |
* When we call new, it is stored on the heap | |
* and has no unexpected behavior. | |
*/ | |
public int RandomInt { get; } = new Random().Next(0, 100); | |
/* | |
* Guid is implemented as a value type (struct). | |
* When we call Guid.NewGuid(), | |
* this value is stored on the stack. | |
* Behind the scenes, the below code creates | |
* a private readonly backing field | |
* and a getter method. | |
* The field value is then set only once. | |
*/ | |
public Guid RandomGuid { get; } = Guid.NewGuid(); | |
// This is roughly the code generated by the above statement. | |
// private readonly Guid _guid = Guid.NewGuid(); | |
// public Guid get_RandomGuid => _guid; | |
} | |
/// <summary> | |
/// Lambda getter-only auto-property | |
/// Not bad, but often misunderstood. | |
/// </summary> | |
public class LamdbaGetterAutoProp | |
{ | |
public int RandomInt => new Random().Next(0, 100); | |
/* | |
* In the above code for generating random numbers, | |
* it is being allocated on the heap, | |
* and we do not notice any difference from our previous method call. | |
* Strangely, the Lambda getter-only auto-property operates differently | |
* and contains potentially unexpected behavior. | |
* Rather than receiving the same value from the last method call, | |
* we receive a new and different value. | |
* The below code is effectively equivalent to this | |
* A new Guid is being created each time this method is called. | |
* | |
* public Guid RandomGuid() => Guid.NewGuid(); | |
* | |
*/ | |
public Guid RandomGuid => Guid.NewGuid(); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment