Search code examples
c#.netpropertiessetter

C# Setter doesn't work at all. It doesn't invoke any code


I'm trying to change Cents in following code. But i 've been stuck for almost an hour. I just can't change this Cents. Setter inside of Cents doesn't work at all. It doesn't change value and even when I make Console.WriteLine("It's been written in Cents setter"); It's not invoked too.

using System;
using System.Collections;
using System.Collections.Generic;
class Program
    {


        static void Main(string[] args)
        {
        BankAccount a = new BankAccount(50,200);
        Console.WriteLine(a.Cents);

        Console.ReadLine();
        }
    }


class BankAccount
{
    public BankAccount(uint dollars,uint cents)
    {
        this.Dollars = dollars;
        this.cents = cents;
    }
    public uint Dollars { get; private set;}
    private uint cents;
    public uint Cents
    {
        get 
        {
            return cents;
        }
        private set
        {
            cents = 500; //It doesnt change
            Console.WriteLine("It's been written in Cents setter"); // I can't invoke it
        }
    }
}

Solution

  • You're mixing up the backing field cents with the property Cents. In the constructor for BankAccount change cents to Cents and the setter will get invoked.

    Also in the setter you probably want to say cents = value