C
C#2y ago
Mochima

Help understanding "get" and "set"

i used to learn c++, now that get and set is really confusing... can it be explained in a way i understand...?
7 Replies
Mochima
MochimaOP2y ago
and how is it useful?
Angius
Angius2y ago
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;
}
}
class Foo {
private:
int bar;

public:
void setBar(int b) {
this.bar = b;
}

int getBar() {
return this.bar;
}
}
The same goes for PHP, Java, and other lesser languages The purpose of it is encapsulation The data itself is always private, internal to the class, to the object The only thing that's public is the accessors of that data 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 That's kinda long, tho, so in C# it's been shortened
Mochima
MochimaOP2y ago
oh
Angius
Angius2y ago
$getsetdevolve
MODiX
MODiX2y ago
class Foo
{
private int _bar;

public int GetBar()
{
return _bar;
}

public void SetBar(int bar)
{
_bar = bar;
}
}
class Foo
{
private int _bar;

public int GetBar()
{
return _bar;
}

public void SetBar(int bar)
{
_bar = bar;
}
}
can be shortened to
class Foo
{
private int _bar;

public int GetBar() => _bar;

public void SetBar(int bar) => _bar = bar;
}
class Foo
{
private int _bar;

public int GetBar() => _bar;

public void SetBar(int bar) => _bar = bar;
}
can be shortened to
class Foo
{
private int _bar;
public int Bar {
get { return _bar; }
set { _bar = value; }
}
}
class Foo
{
private int _bar;
public int Bar {
get { return _bar; }
set { _bar = value; }
}
}
can be shortened to
class Foo
{
private int _bar;
public int Bar {
get => _bar;
set => _bar = value;
}
}
class Foo
{
private int _bar;
public int Bar {
get => _bar;
set => _bar = value;
}
}
can be shortened to
class Foo
{
public int Bar { get; set; }
}
class Foo
{
public int Bar { get; set; }
}
Angius
Angius2y ago
Here's a nice lil' breakdown
Mochima
MochimaOP2y ago
thanks for that
Want results from more Discord servers?
Add your server