0

I can not understood why this code doesn't changing value from null(compiler even can't see that null instead of that Im reciving blank spots)

 public string? ClubName
        {
            get => _clubname;

            set
            {
                _clubname = value ?? "it";
            }
        } 

enter image description here

3
  • Can you show how you are using that property? Show the value of the property before an assignment to it, show how you make the assignment. Then show us the value of the property after the assignment. Basically, let us step through your code Commented Oct 22, 2022 at 17:59
  • 1
    At no point is the setter for ClubName called in the code you posted, therefore it will have it's default value of null. If you write Console.WriteLine(null) it won't crash - it will just be the same as Console.WriteLine("") Commented Oct 22, 2022 at 18:06
  • 1
    Because property setters are not called when you construct an object, but only when actually set the property. Commented Oct 22, 2022 at 18:06

1 Answer 1

2

Your setter uses the null-coalescing operator ??, which substitutes "it" should value be null:

_clubname = value ?? "it";

So, you can never assign null to the property via the setter.

However, your property is backed by this private field:

_string clubname;

which the compiler initializes to null.

While you can never set null, the code in your screenshot never assigns a value, so the initial value remains.

Sign up to request clarification or add additional context in comments.

5 Comments

I think you misunderstand the question: " why this code doesn't changing value from null" - note FROM null.
Ah. Because you never set a value, and _clubname is initialized to null by default.
Updated my answer accordingly.
that make a sense, thanks so much! I overlooked that
@PoulBak: note that the question has been edited three times, taking it from nearly incomprehensible (the version this answer attempts to respond to) to merely confusing. I would not have guessed what the question was from the first version

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.