C
C#2mo ago
nah, i'd win

set with different values

hey everyone, i am a total noob and i want to ask if there is a way for set having different values with different conditions? like
private bool Bool1;

public bool Bool2
{
get => Bool1;
if (a = 1) {
set => Bool2 = true;
}
else {
set => Bool2 = false;
}
}
private bool Bool1;

public bool Bool2
{
get => Bool1;
if (a = 1) {
set => Bool2 = true;
}
else {
set => Bool2 = false;
}
}
14 Replies
Unknown User
Unknown User2mo ago
Message Not Public
Sign In & Join Server To View
TheRanger
TheRanger2mo ago
even if they did it will throw stack overflow exception
Pobiega
Pobiega2mo ago
its also violating "the rule of least surprise" a setter not setting a value I give it is very surprising
TheRanger
TheRanger2mo ago
private bool Bool1;

public bool Bool2
{
get => Bool1;
set
{
if (a == 1)
{
Bool1 = true;
}
else
{
Bool1 = false;
}
}
}
private bool Bool1;

public bool Bool2
{
get => Bool1;
set
{
if (a == 1)
{
Bool1 = true;
}
else
{
Bool1 = false;
}
}
}
Alen Alex
Alen Alex2mo ago
Honestly ig, it is better to extract that logic to a method…I don’t think it should be the job of setters
TheRanger
TheRanger2mo ago
it is, thats one of the main reasons properties exist
nah, i'd win
nah, i'd win2mo ago
nah i just have a code that requieres setters sorry if i spelt it wrong
Pobiega
Pobiega2mo ago
x.Bool2 = true;
if(x.Bool2) // this wont run????
x.Bool2 = true;
if(x.Bool2) // this wont run????
this would be a potential result from the above and make me throw your code in the nearest garbage bin
nah, i'd win
nah, i'd win2mo ago
😔
Pobiega
Pobiega2mo ago
if I set it to true, and thats not allowed, throw an exception dont silently set it to false instead
TheRanger
TheRanger2mo ago
setting Bool2 to false or true wont make a difference, because your setter never reads the value
Vi Ness
Vi Ness2mo ago
Based on the code given, my interpretation was they wanted something more akin to
private int a;

public bool Bool1
{
get => (a == 1);
}
private int a;

public bool Bool1
{
get => (a == 1);
}
But they said the code requires setters so idk
Pobiega
Pobiega2mo ago
yeah, which absolutely fucks with your expectations if I set it to true, I expect it to be true, or throw an exception
Alen Alex
Alen Alex2mo ago
I too somehow agree with that, silently modifying it internally will be a disaster sometimes Yes, I would expect it to compute the value based on the input (value that I set), not based on some random value a. If I set Bool2 = true and the state got changed due to some other random variable seems a bit off for me. I don't think thats an actual behaviour of setter.