locked
adding two public variables after declaration and assignment RRS feed

  • Question

  • User379720387 posted

        public decimal primaryCharges { get; set; } = 0;
        public decimal addOnCharges { get; set; } = 0;
        public decimal ServiceCharges { get; set; } = primaryCharges + addOnCharges;

    Error message (same for addOnCharges):

    A field initializer cannot reference the non-static field, method, or property 'primaryCharges' 

    Wednesday, March 31, 2021 5:53 PM

Answers

All replies

  • User475983607 posted

    The syntax is...

            public decimal primaryCharges { get; set; } 
            public decimal addOnCharges { get; set; }
            public decimal ServiceCharges
            {
                get
                {
                    return primaryCharges + addOnCharges;
                }
            }

    Zero is the default value of a decimal so there is not need to initialize the property with a zero.

    C# Programming guide

    https://docs.microsoft.com/en-us/dotnet/csharp/programming-guide/classes-and-structs/properties

    https://docs.microsoft.com/en-us/dotnet/api/system.decimal?view=net-5.0

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Wednesday, March 31, 2021 6:51 PM
  • User379720387 posted

    Thnx!

    It is amazing the stuff that is on that Microsoft site, if you can find it.

    To make this thread complete, I also needed the set as per below.

    public decimal ServiceCharges  { 
            get
            {
                return primaryCharges + addOnCharges;
            }
            set { }
        }

    Wednesday, March 31, 2021 7:58 PM
  • User475983607 posted

    wavemaster

    To make this thread complete, I also needed the set as per below.

    Um no.  The get will always return primaryCharges + addOnCharges.  Do you have other logic that you did not tell us about?  

    Wednesday, March 31, 2021 8:33 PM