Home > Back-end >  Properties of C# set and get
Properties of C# set and get

Time:12-18

I printed it to the console and it wrote me false.

bool _turnedOn, _turnedOff;

public bool Start { get => _turnedOn; private set => _turnedOn = true; }

Why it returns false if I set the variable to true?

CodePudding user response:

bool _turnedOn, _turnedOff;

These are both false. When you access Start, it's going to give you _turnedOn, which is false. It doesn't get set to true until you try to set Start to anything, because you've defined the setter as _turnedOn = true.

If you declare it as bool _turnedOn = true; then you'll get what you want I think, but I don't understand the point. Why bother with a value that you want to be always true?

CodePudding user response:

In C# (and most languages), booleans are set to False by default.

The default value of the bool type is false.

https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/builtin-types/bool


In addition, it is best practice to directly specify the default value on variable creation, along with placing them on separate lines.

I'm also not sure of the use case, but using a single bool might be better than having two?

CodePudding user response:

Bool in ‘c#’ defaults to false.

And since Start isn’t initialized to ‘true’ it defaults to false.

When using private setter you need to set it in the constructor like so

‘’’csharp

Class StartClass{

    StartClass()
   {
       Start = true;
   }

}

‘’’

  • Related