C
C#14mo ago

✅ C# best practices clarification

By convention, which is preferable to use? Getter and Setter methods or properties? Are the equivalent? Or is there a benefit to either? (I'm still new to C#).
No description
6 Replies
Angius
Angius14mo ago
Properties We ain't writing Java around these parts
fæ
OP14mo ago
lolll straightforward is there a reason why visual studio offers that as a "refactoring"? is that a style microsoft supports/ are there C# coders in the wild that are doing it that way? (kinda offtopic question but yeah)
Angius
Angius14mo ago
Some learning-averse Java refugees might still be writing boilerplate getters and setters ig Besides that, no idea why would anybody write out setter and getter methods Not sure why it's a refactoring either I'd sooner expect one that simply introduces a backing field, but still utilizes the property $getsetdevolve
MODiX
MODiX14mo 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
Angius14mo ago
Refactoring to step 3 or 4 on this scale Not to step 1
fæ
OP14mo ago
good stuff.thanks!
Want results from more Discord servers?
Add your server