Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Difference between Expression-Bodied Properties and simple Getter Properties

Tags:

c#

.net

After reading some source code of different c# project i noticed different ways of writing (almost) the same statement regarding public "getter" and private "setter" properties.

First way with only properties:

public int x { get; private set; }

Second way with expression-bodied properties:

private int _x;
public int x => _x;

I know that public int x { get; } is equivalent to

private readonly int __x;
public int x { get { return __x } }

So I understand the difference between expression-bodied and normal properties in the case of a single "getter". What i do not understand is the difference when there is a private field that holds the referenced value. I thought that maybe the second one is faster because you have access to the field directly instead of a method call inside your class. Is it just a stylistic difference or is one of the examples faster, more robust, etc?

like image 293
number2 Avatar asked Sep 15 '25 09:09

number2


1 Answers

You have two groups of constructs which are equivalent.

Group 1

When you don't need write access to the backing field outside the constructor, you can use any of these constructs:

private readonly int _x;
public int x => _x;

or

private readonly int _x;
public int x { get => _x; }

or

private readonly int _x;
public int x { get { return _x; } }

or

public int x { get; }

Group 2

When you need access to the backing field outside the constructor, you can use any of these constructs:

private int _x;
public int x => _x;

or

private int _x;
public int x { get => _x; }

or

private int _x;
public int x { get { return _x; } }

or

public int x { get; private set; }

You can expect all of the alternatives to be equally fast. In the last construct the compiler will inject a setter method (it will inject a backer field too, as for every automatic property). In the other cases you access the field directly. The injected setter will almost certainly be inlined by the jitter, which removes the performance penalty of a method call. Check this Q&A for details on JIT inlining.

The automatic property is certainly more concise, which makes your code neater, especially when you have many properties. But at the end of the day it comes down to personal preference (or your team's coding rules).

like image 165
Sefe Avatar answered Sep 17 '25 21:09

Sefe



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!