C
C#2y ago
Matt

❔ What is the difference between these two pieces of code?

static PlayerHandler HPlayer => Program.HPlayer;
static PlayerHandler HPlayer => Program.HPlayer;
static PlayerHandler HPlayer = Program.HPlayer;
static PlayerHandler HPlayer = Program.HPlayer;
In essence I'm asking what the purpose of the lambda is here? I've used this pattern to help with a loose singleton pattern for a long time but I have no idea what this is even doing or why I use => over =
6 Replies
phaseshift
phaseshift2y ago
It's not a lambda , it's a property (get only) The second is a field.
Matt
MattOP2y ago
Okay I know that much but when I'm researching properties I can't find anything using this syntax or explaining it. I don't even know where I picked it up from. In my mind, the way I've been thinking of it is that if I use => I'm saying that the field I'm declaring IS the thing from the other class so no new variable is really created, the one I'm declaring just points to the already existing variable whereas if I use =, I'm creating a copy of the variable I've assigned. Is that even close?
phaseshift
phaseshift2y ago
No, not close 😁 To be technical, it's called an expression bodied property It means every time the getter is called return the thing on the rhs The field assignment you have means, at initialization, set the value to the rhs, and forever return that initial value. Everything is by reference for classes
Anton
Anton2y ago
that's short for
static T prop
{
get
{
return Program.HPlayer;
}
}
static T prop
{
get
{
return Program.HPlayer;
}
}
Yashe
Yashe2y ago
The first one is body expresion of a property as phaseshift already tell. When you are using '=' sign you are declearing a field and assigning a value : variable = value With this '=>' you are referencing something for example it can be simple as: public int Score => score : this propery reference to an existing score field variable or public int Health => playerController.Health : in this case you are referencing something from another class for example But you can do more complex stuff and for example make a property which will return some element from a list, or do some mathfs before. If the player max health is 100, current is 65 and you want a field that represents the missing health you can make a private property: private int MissingHealth => MaxHealth - CurrentHealth and you can't do it while declaring the variable
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.
Want results from more Discord servers?
Add your server