C
C#2mo ago
mack

✅ get set help

i dont understand the application of a get set method. are there any practical examples you can give?
4 Replies
Jimmacle
Jimmacle2mo ago
in C# we don't use get and set methods, we use properties that accomplish the same thing
int MyProperty { get; set; }
int MyProperty { get; set; }
basically, the reason to use them is that so the class has full control over its data for example, maybe you don't want outside the class to change the value in which case you'd make the setter private
int MyProperty { get; private set; }
int MyProperty { get; private set; }
or you want to do some validation of the value
private int _myField;

public int MyProperty
{
get => _myField;
set
{
if (value > 100)
throw new Exception("Number is too big");

_myField = value;
}
}
private int _myField;

public int MyProperty
{
get => _myField;
set
{
if (value > 100)
throw new Exception("Number is too big");

_myField = value;
}
}
mack
mack2mo ago
ah, so another class can reference MyProperty and that gives the value of _myField
Jimmacle
Jimmacle2mo ago
yes, but the class that contains MyProperty has control over what other classes can change the value to since it has to go through the setter or if you wanted to change the value to be calculated by some other process, you can change that inside the class without other classes needing to know or be updated
mack
mack2mo ago
thank you discord user amogus jimmacle i understand better now
Want results from more Discord servers?
Add your server