Search code examples
c#getter-setter

C# - Getter and Setter dosen't keep the value


Here is my code:

private int pressedMain = 1;

public int PressedMain
{
    get
    {
        return pressedMain;
    }

    set
    {
        pressedMain = value;
    }
}

And then I change the value of pressedMain:

pw.PressedMain++;

But in the following class my value is one, why and how can I slove this problem?


Solution

  • Example invoke, console prints 2 here

      public class Foo
        {
            private int pressedMain = 1;
            public int PressedMain
            {
                get
                {
                    return pressedMain;
                }
    
                set
                {
                    pressedMain = value;
                }
            }
        }
        class Program
        {
    
            static void Main(string[] args)
            {
    
                Foo foo = new Foo();
                foo.PressedMain++;
    
                Console.WriteLine(foo.PressedMain);
    
                Debugger.Break();
            }
        }