C
C#15mo ago
Emelie

❔ Property vs field?

Hi everyone, I have a really basic but also really important question regarding C#. I have been coding for some time now, and I am using properties and fields as I have been instructed to in my classes, but still I don´t really grasp the difference. What is actually the difference? been reading online but these explanations don´t seem to do it for me :/
27 Replies
Angius
Angius15mo ago
Rule of thumb: private fields, public properties Properties allow for better encapsulation Using them means the underlying field is never accessed directly, they create a layer of insulation and protect from unforseen results of API changes
Emelie
EmelieOP15mo ago
yeah, but what does it actually mean? like I understand the basic concept of encapsulation, but I think I would need a practical example, if thats possible? like, what could be a real-life consequence of not having proper encapsulation when needed?
Angius
Angius15mo ago
For example, if you suddenly need to validate that a certain field is no less than 10, you would need to change all object.Field = value into object.SetField(value) With properties it's not an issue, you just put the validation code in the setter And object.Prop = value remains object.Prop = value, but now is validated It doesn't break the code that calls it Properties are a shortcut for getters and setters you might know from lesser languages like Java or C++ $getsetdevolve
MODiX
MODiX15mo 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
Angius15mo ago
Properties also allow for more granular access control A public field will be public, in it's entirety A property can be public but have a private setter A property can also have an initializer instead of a setter, making it immutable
Emelie
EmelieOP15mo ago
No description
Emelie
EmelieOP15mo ago
this part I dont fully understand could you perhaps give me an example with the validation above? 🙂 🙌☺️
Angius
Angius15mo ago
private int _age;
public int Age {
get => _age;
set => _age = value is > 0 and < 150
? value
: throw new ArgumentException();
}
private int _age;
public int Age {
get => _age;
set => _age = value is > 0 and < 150
? value
: throw new ArgumentException();
}
For example this If you try to set age lower than 0 or higher than 150, it will throw an exception Or this,
private string _name;
public string Name {
get => _name;
set => _name = value[..15];
}
private string _name;
public string Name {
get => _name;
set => _name = value[..15];
}
which will automatically truncate the value to 15 characters
Emelie
EmelieOP15mo ago
private int _age; public int Age { get => _age; set => _age = value is > 0 and < 150 ? value : throw new ArgumentException(); } so this one.. the error would be prevented with a property?
Pobiega
Pobiega15mo ago
The property allows validation, while a field does not
Angius
Angius15mo ago
No, the error would be thrown with this property Not prevented Thing is, you cannot say "this field should be in range between 0 and 150, otherwise it's an error" But you can say "this property should be in range between 0 and 150, otherwise it's an error"
Emelie
EmelieOP15mo ago
soo a field should merely tell the programme which variables we want to use, and a property allows us to modify those variables?
Angius
Angius15mo ago
Fields are the internal state of the object Properties allow us to look at them (if allowed) and modify them (if allowed)
Pobiega
Pobiega15mo ago
var person = new Person();
person.age = -5; // this is allowed, and can't be prevented
person.Age = -5; // this will throw an error

public class Person
{
public int age = 0;

public int Age
{
get => age;
set => age = value is >= 0 and <= 150 ? value : throw new ArgumentException("Trying to set invalid value on Person.Age");
}
}
var person = new Person();
person.age = -5; // this is allowed, and can't be prevented
person.Age = -5; // this will throw an error

public class Person
{
public int age = 0;

public int Age
{
get => age;
set => age = value is >= 0 and <= 150 ? value : throw new ArgumentException("Trying to set invalid value on Person.Age");
}
}
Emelie
EmelieOP15mo ago
I think Im getting it because fields should pretty much always be private?
Pobiega
Pobiega15mo ago
yes
Angius
Angius15mo ago
Yep
MODiX
MODiX15mo ago
Angius
Rule of thumb: private fields, public properties
Quoted by
<@85903769203642368> from #Property vs field? (click here)
React with ❌ to remove this embed.
Pobiega
Pobiega15mo ago
otherwise you are allowing unfiltered access to it from anywhere, and that access can do whatever it wants to the value. setting it to 0, setting it to int.MaxValue etc and this might break your domain rules for this object. thats why properties exist, so you can codify those rules and be sure
Emelie
EmelieOP15mo ago
so the error thrown when we try to set the age to -5 is actually a thing we WANT to do? I think Im automatically thinking that errors is a bad thing so properties are almost another way of saying "validation method"? they are input validation methods to make sure that the objects values are reasonable
Angius
Angius15mo ago
Yes, we want to throw the error
Pobiega
Pobiega15mo ago
the error prevents -5 from being set. if you are writing it in code, you want the error so you can see "ah wait, im breaking my own rules here!"
Emelie
EmelieOP15mo ago
thank you!! I finally understand it 🙂
Pobiega
Pobiega15mo ago
and if you are getting the value from user input, you want the error (but catching it) so you can tell the user "you tried to set an invalid value!"
Angius
Angius15mo ago
As a side note and an interesting piece of trivia, there are languages out there who have validation as a part of their type system. Can't remember their names or the specific syntax, but you can use them to do, say
public someFunction(
name: string [ length > 3, length < 40 ],
age: int [ > 0, < 150 ],
)
public someFunction(
name: string [ length > 3, length < 40 ],
age: int [ > 0, < 150 ],
)
Pobiega
Pobiega15mo ago
F# allows this more or less
Accord
Accord15mo 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