❔ Are these properties the same? `{ get => x; }` vs `{ get; } = x;`
I would like to know if these have any other differences besides the syntax.
Case 1:
public int TileSize { get; } = 64;
Case 2:
public int TileSize { get => 64; }
In my code below I have other properties that use the 2nd case, but that's because of more specific reasons, for example:
I'm not sure which one would be better in the long run (if there are no other differences).
Previously I always used the 1st case, but here 2nd case seems more consistent with properties below, so this leaves a little confused as I never even thought about the 2nd case.5 Replies
public int TileSize { get; } = ...;
sets the value of the property when the object is created and returns that value every time the property is accessed.
public int TileSize { get => 64; }
or just public int TileSize => 64;
returns the value 64
every time.
might not seem like there's a difference, but if you for instance are accessing something which can change in the getter, then the value you get from the property can change every time you access it if you just use => 64;
It really depends on how you want your property to act. In this case it looks like the data will be unchanging, so using { get; } =
would be the most beneficial.Thanks that makes sense
You can essentially think about it like this becomes
Notice that
A
is getting the same value every time, while B
is calling GetData()
every time.makes sense
Was this issue resolved? If so, run
/close
- otherwise I will mark this as stale and this post will be archived until there is new activity.