C
Join ServerC#
help
Help understanding "get" and "set"
MMochima1/29/2023
i used to learn c++, now that get and set is really confusing...
can it be explained in a way i understand...?
can it be explained in a way i understand...?
MMochima1/29/2023
and how is it useful?
AAngius1/29/2023
In C++ you might've used getter and setter functions, like
class Foo {
private:
int bar;
public:
void setBar(int b) {
this.bar = b;
}
int getBar() {
return this.bar;
}
}
AAngius1/29/2023
The same goes for PHP, Java, and other lesser languages
AAngius1/29/2023
The purpose of it is encapsulation
AAngius1/29/2023
The data itself is always private, internal to the class, to the object
AAngius1/29/2023
The only thing that's public is the accessors of that data
AAngius1/29/2023
It gives you full control over the mutation of the internal state of the class. You can disallow setting it if you want, you can add some logic to the getter, whatever you need
AAngius1/29/2023
That's kinda long, tho, so in C# it's been shortened
MMochima1/29/2023
oh
AAngius1/29/2023
$getsetdevolve
MMODiX1/29/2023
class Foo
{
private int _bar;
public int GetBar()
{
return _bar;
}
public void SetBar(int bar)
{
_bar = bar;
}
}
can be shortened toclass Foo
{
private int _bar;
public int GetBar() => _bar;
public void SetBar(int bar) => _bar = bar;
}
can be shortened toclass Foo
{
private int _bar;
public int Bar {
get { return _bar; }
set { _bar = value; }
}
}
can be shortened toclass Foo
{
private int _bar;
public int Bar {
get => _bar;
set => _bar = value;
}
}
can be shortened toclass Foo
{
public int Bar { get; set; }
}
AAngius1/29/2023
Here's a nice lil' breakdown
MMochima1/29/2023
thanks for that