Home > Blockchain >  explain public variable ; (vs) public variable {get; set;} difference in C#?
explain public variable ; (vs) public variable {get; set;} difference in C#?

Time:05-18

Similar questions has been asked a lot but it still doesn't make sense to me as I am beginner.

here is the link

decompiled Dog class

Notice the Name property is there as you'd expect, with its getter and setter. But notice also the k__BackingField.

When we inspect it, it is comprised of the following code:

[CompilerGenerated]
[DebuggerBrowsable(DebuggerBrowsableState.Never)]
private string <Name>k__BackingField;

So we can see that there is definitely a private field in the background being generated for the property. We can also confirm that it actually uses that field by inspecting the get_Name getter on the Name property:

[CompilerGenerated]
{
    return <Name>k__BackingField;
}

The getter for the Name property indeed returns the private field that was compiler generated for us.

I think what you're stuck on is why we would do this. Basically, if you simply have a public field on a class, you're giving permission for all-and-any other classes to set and get that field without any kind of checks or balances or rules about what goes on when setting or retrieving that value. For small applications that aren't very complex, this won't create an issue for you. But in the future when you're writing bigger applications or libraries, when you want to guarantee certain functionality behaves the same way all the time, this best practice will be necessary.

CodePudding user response:

There is no difference when you use them as simple variables but using a variable as property gives you the ability to perform a check or create an event handler. For example:

private int _onetoten;
public int OneToTen
    {
        get => _onetoten;
        set
        {
            if ((value > 0) && (value < 11))
            {
                _onetoten = value;
            }
        }
    }
  • Related