Why does the backing field of my property not change its value?

前端 未结 1 814
悲哀的现实
悲哀的现实 2021-01-21 11:48
namespace tutor4
{
    class Class1
    {
        int _num = 2;
        public int num
        {
            get
            {
                return _num;
            }         


        
相关标签:
1条回答
  • 2021-01-21 12:39

    Your setter for num property is wrong.

    It should not be

    set
    {
         _num = num;
    }
    

    because in this case it does nothing (sets _num back to its value since getter for num returns _num so this line is equivalent to _num = _num)

    It should be

    set
    {
         _num = value;
    }
    

    MSDN explanation about value keyword:

    The contextual keyword value is used in the set accessor in ordinary property declarations. It is similar to an input parameter on a method. The word value references the value that client code is attempting to assign to the property

    Also note: your num property is just simple wrapper of _num field of class. If you don't need some complex logic in getter and setter for this property - you can change it to auto-implemented property like this:

    class Class1
    {
        public int num { get; set;}
    
        public Class1
        {
            num = 2;
        }
    }
    

    Until C# version 6 you should assign default value to auto-implemented property in class constructor.

    In C# version 6 (not yet released, should be available this summer) you will be able to assign default value to auto-implemented property in declaration:

    public int num { get; set;} = 2;
    
    0 讨论(0)
提交回复
热议问题