C
C#10mo 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
Angius10mo 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
Emelie10mo 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
Angius10mo 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
MODiX10mo 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
Angius10mo 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
Emelie10mo ago
No description
Emelie
Emelie10mo ago
this part I dont fully understand could you perhaps give me an example with the validation above? 🙂 🙌☺️
Angius
Angius10mo 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
Emelie10mo 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
Pobiega10mo ago
The property allows validation, while a field does not
Angius
Angius10mo 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
Emelie10mo 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
Angius10mo ago
Fields are the internal state of the object Properties allow us to look at them (if allowed) and modify them (if allowed)
Pobiega
Pobiega10mo 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
Emelie10mo ago
I think Im getting it because fields should pretty much always be private?
Pobiega
Pobiega10mo ago
yes
Angius
Angius10mo ago
Yep
MODiX
MODiX10mo 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
Pobiega10mo 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
Emelie10mo 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
Angius10mo ago
Yes, we want to throw the error
Pobiega
Pobiega10mo 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
Emelie10mo ago
thank you!! I finally understand it 🙂
Pobiega
Pobiega10mo 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
Angius10mo 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
Pobiega10mo ago
F# allows this more or less
Accord
Accord10mo 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
More Posts
❔ [EFCore] What is the right approach to generate hierarchy id for new child entity?I Use SQLServer & EF Core. been struggling to find the right approach to generate new h-id for new ✅ ConstructorsIf Constructors are just a method called when a class is created, how does the new operator in combi❔ Conditional in semantic kernel (skprompt.txt file)Hey guys, I currently using semantic kernel to do stuff related with AI in my console app. In sema❔ Can I/How would I do these things with CefGlue.Avalonia?So im trying to make something, but idk what to do because im not sure how much of this can even be ❔ how can i save flow layout panelim doing a simple video game library with C# but the problem is i cant save them when i add new pane❔ Is it possible to log for the user (not dev) with localization?Given that a multi-lingual app exists And it is currently configured to some language When somethingHow to sort a list of a class by property using LINQ when the name of the property comes from inputSo, im learning c# and im trying to solve an exercise. The issue im facing is, i have a class that h❔ Organising some CodeSo I've been doing leetcode to become better at cracking problems and becoming more efficient at cod✅ Server side or Client side?Hi, finally i get to MVC and it looks much easier then work with minmal api, so i have some question✅ What's the point of MediatR?I haven't done *a lot* of web/API dev, so this might just be because I've never been in a situation