C
C#2y ago
lukkasz323

❔ 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:
public (int x, int y) Center

{

get => (_terrain.GetLength(1) / 2, _terrain.GetLength(0) / 2);

}
public (int x, int y) Center

{

get => (_terrain.GetLength(1) / 2, _terrain.GetLength(0) / 2);

}
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
Thinker
Thinker2y ago
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.
lukkasz323
lukkasz3232y ago
Thanks that makes sense
Thinker
Thinker2y ago
You can essentially think about it like this
class Class
{
public int A { get; } = GetData();
public int B => GetData();
}
class Class
{
public int A { get; } = GetData();
public int B => GetData();
}
becomes
class Class
{
private readonly int a;

public int A
{
get
{
return a;
}
}
public int B
{
get
{
return GetData();
}
}

public Class()
{
a = GetData();
}
}
class Class
{
private readonly int a;

public int A
{
get
{
return a;
}
}
public int B
{
get
{
return GetData();
}
}

public Class()
{
a = GetData();
}
}
Notice that A is getting the same value every time, while B is calling GetData() every time.
lukkasz323
lukkasz3232y ago
makes sense
Accord
Accord2y ago
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.