Skip to content

Instantly share code, notes, and snippets.

@rcook
Created February 23, 2022 18:56
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save rcook/5e89e583a458baf85f77dfe7a24ba16d to your computer and use it in GitHub Desktop.
Save rcook/5e89e583a458baf85f77dfe7a24ba16d to your computer and use it in GitHub Desktop.
Different C# property syntaxes
var x = new MyClass(100, 200);
Console.WriteLine(x.Property0);
Console.WriteLine(x.Property1);
Console.WriteLine(x.Property2);
Console.WriteLine(x.Property3);
Console.WriteLine(x.Property4);
class MyClass
{
public MyClass(int property0, int property1)
{
}
public void SomeMethod()
{
}
// Generates an anonymous "init-only" backing field with default value (0)
// Class's constructor implicitly initializes backing field to 1000
// Class's constructor can assign property value but other members cannot
public int Property0 { get; } = 1000;
// Generates an anonymous "init-only" backing field with default value (0)
// Class's constructor can assign property value but other members cannot
public int Property1 { get; }
// Generates an anonymous backing field (not "init-only") with default value (0)
// Class's constructor can assign property value
// Other methods in class can also assign property value
public int Property2 { get; private set; }
// Generates an anonymous backing field (not "init-only") with default value (0)
// Class's constructor implicitly initializes backing field to 5000
// Class's constructor can assign property value
// Other methods in class can also assign property value
public int Property3 { get; private set; } = 5000;
// Does not generate a backing field
// Property calls lambda which evaluates to 2000
// Neither constructor nor other members can assign values
public int Property4 => 2000;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment