Skip to content
  • Categories
  • Recent
  • Tags
  • Popular
  • World
  • Users
  • Groups
Skins
  • Light
  • Cerulean
  • Cosmo
  • Flatly
  • Journal
  • Litera
  • Lumen
  • Lux
  • Materia
  • Minty
  • Morph
  • Pulse
  • Sandstone
  • Simplex
  • Sketchy
  • Spacelab
  • United
  • Yeti
  • Zephyr
  • Dark
  • Cyborg
  • Darkly
  • Quartz
  • Slate
  • Solar
  • Superhero
  • Vapor

  • Default (No Skin)
  • No Skin
Collapse
Code Project
  1. Home
  2. General Programming
  3. C#
  4. C# using get set. Why is this failing?

C# using get set. Why is this failing?

Scheduled Pinned Locked Moved C#
csharphelpquestion
33 Posts 9 Posters 0 Views 1 Watching
  • Oldest to Newest
  • Newest to Oldest
  • Most Votes
Reply
  • Reply as topic
Log in to reply
This topic has been deleted. Only users with topic management privileges can see it.
  • B Offline
    B Offline
    Brian_TheLion
    wrote on last edited by
    #1

    I can't see the reason why this does not work. There is no clear indication what the error is.

    public int CurrentHitPoints { get; set; }
    public int MaximumHitPoints { get; set; }
    public int Gold
    {
    get
    {
    return Gold;
    }

            set
            {
                if (value == 20)
               {
                  value += 5;
                  Gold = value;
               }
            }
        }
        public int ExperiencePoints { get; set; }
        public int Level { get; set; }
    

    Brian

    M L OriginalGriffO L 4 Replies Last reply
    0
    • B Brian_TheLion

      I can't see the reason why this does not work. There is no clear indication what the error is.

      public int CurrentHitPoints { get; set; }
      public int MaximumHitPoints { get; set; }
      public int Gold
      {
      get
      {
      return Gold;
      }

              set
              {
                  if (value == 20)
                 {
                    value += 5;
                    Gold = value;
                 }
              }
          }
          public int ExperiencePoints { get; set; }
          public int Level { get; set; }
      

      Brian

      M Offline
      M Offline
      Member 13566383
      wrote on last edited by
      #2

      What do you mean by "is failing"?

      B 1 Reply Last reply
      0
      • M Member 13566383

        What do you mean by "is failing"?

        B Offline
        B Offline
        Brian_TheLion
        wrote on last edited by
        #3

        I get this popup box An unhandled exception of type 'System.StackOverflowException' occurred in Engine.dll Engine is a container for player.cs Brian

        M 1 Reply Last reply
        0
        • B Brian_TheLion

          I get this popup box An unhandled exception of type 'System.StackOverflowException' occurred in Engine.dll Engine is a container for player.cs Brian

          M Offline
          M Offline
          Member 13566383
          wrote on last edited by
          #4

          You are calling your get- and set-properties for "Gold" recursively.

          B 1 Reply Last reply
          0
          • M Member 13566383

            You are calling your get- and set-properties for "Gold" recursively.

            B Offline
            B Offline
            Brian_TheLion
            wrote on last edited by
            #5

            This is the code that player.cs is called from. I added a TEST button. lblGold.text is a label on the form.

            using Engine;

            namespace SuperAdventure
            {
            public partial class SuperAdventure : Form
            {
            private Player _player;

                public SuperAdventure()
                {
                    InitializeComponent();
            
                    Location location = new Location(1, "Home", "This is your house.");
            
            
                    \_player = new Player(10, 10, 20, 0, 1);
                    
                    Update();
            
                }
            
                private void btnTest\_Click(object sender, EventArgs e)
                {
                    \_player.Gold = 30;
                    //  lblGold.Text = \_player.Gold.ToString();
                    Update();
                }
                      public void  Update()
                  {
                    lblHitPoints.Text = \_player.CurrentHitPoints.ToString();
                    lblGold.Text = \_player.Gold.ToString();
                    lblExperience.Text = \_player.ExperiencePoints.ToString();
                    lblLevel.Text = \_player.Level.ToString();
                }
            }
            

            }

            1 Reply Last reply
            0
            • B Brian_TheLion

              I can't see the reason why this does not work. There is no clear indication what the error is.

              public int CurrentHitPoints { get; set; }
              public int MaximumHitPoints { get; set; }
              public int Gold
              {
              get
              {
              return Gold;
              }

                      set
                      {
                          if (value == 20)
                         {
                            value += 5;
                            Gold = value;
                         }
                      }
                  }
                  public int ExperiencePoints { get; set; }
                  public int Level { get; set; }
              

              Brian

              L Offline
              L Offline
              lmoelleb
              wrote on last edited by
              #6

              Your highest priority should be to learn to use the debugger. It might sound advanced... but it isn't. You will be able to spot the course of errors like this in seconds - even without a heap of experience. Sure some errors will still be tricky... but if they are tricky with a debugger, they are pretty much impossible to solve without. All you have to do is set a break point in the code you see a problem with (F9 in Visual Studio default key binding). Start the program with the debugger attached (F5) and reproduce the problem. Now you can step through the program line by line (F10/F11)- and you can see the values of all variables and fields at each line in the program. Spotting the setter calling itself is trivial this way. As a beginner you might still want to ask help on how to solve a problem once you identified it - but at least you can ask a much more precise question when you know what the error is - and get help a lot easier. So please - take the time to learn the debugger. The half hour will come back with interest of a few million percent.

              B K 2 Replies Last reply
              0
              • B Brian_TheLion

                I can't see the reason why this does not work. There is no clear indication what the error is.

                public int CurrentHitPoints { get; set; }
                public int MaximumHitPoints { get; set; }
                public int Gold
                {
                get
                {
                return Gold;
                }

                        set
                        {
                            if (value == 20)
                           {
                              value += 5;
                              Gold = value;
                           }
                        }
                    }
                    public int ExperiencePoints { get; set; }
                    public int Level { get; set; }
                

                Brian

                OriginalGriffO Offline
                OriginalGriffO Offline
                OriginalGriff
                wrote on last edited by
                #7

                Look at your code.

                public int Gold
                {
                get
                {
                return Gold;
                }
                ...
                }

                So now lets use it:

                int g = myClassInstance.Gold;

                It enters the Gold getter, which returns the value of ... the Gold getter. Which returns the value of ... the Gold getter. Which returns the value of ... the Gold getter. ... until the stack blows and your app crashes. The same happens when you try to use the setter: it infinitely recurses trying to set itself! Create a private backing field:

                private int _Gold = 0;
                public int Gold
                {
                get
                {
                return _Gold;
                }

                set
                    {
                    if (value == 20)
                        {
                        value += 5;
                        \_Gold = value;
                        }
                    }
                }
                

                And it'll all work.

                Sent from my Amstrad PC 1640 Never throw anything away, Griff Bad command or file name. Bad, bad command! Sit! Stay! Staaaay... AntiTwitter: @DalekDave is now a follower!

                "I have no idea what I did, but I'm taking full credit for it." - ThisOldTony
                "Common sense is so rare these days, it should be classified as a super power" - Random T-shirt

                B 1 Reply Last reply
                0
                • L lmoelleb

                  Your highest priority should be to learn to use the debugger. It might sound advanced... but it isn't. You will be able to spot the course of errors like this in seconds - even without a heap of experience. Sure some errors will still be tricky... but if they are tricky with a debugger, they are pretty much impossible to solve without. All you have to do is set a break point in the code you see a problem with (F9 in Visual Studio default key binding). Start the program with the debugger attached (F5) and reproduce the problem. Now you can step through the program line by line (F10/F11)- and you can see the values of all variables and fields at each line in the program. Spotting the setter calling itself is trivial this way. As a beginner you might still want to ask help on how to solve a problem once you identified it - but at least you can ask a much more precise question when you know what the error is - and get help a lot easier. So please - take the time to learn the debugger. The half hour will come back with interest of a few million percent.

                  B Offline
                  B Offline
                  Brian_TheLion
                  wrote on last edited by
                  #8

                  I normally have an error message popup that tells me e exactly what is wrong (in most cases it's a spelling mistake) but this time this did not happen. I have stepped through programs to see how they work. I could try doing that but I suspect all that would happen is the same message would pop up which does not tell me exactly what is wrong. However a popup box with same message is better than nothing. I may need to research this message on the internet Brian

                  L M D 3 Replies Last reply
                  0
                  • OriginalGriffO OriginalGriff

                    Look at your code.

                    public int Gold
                    {
                    get
                    {
                    return Gold;
                    }
                    ...
                    }

                    So now lets use it:

                    int g = myClassInstance.Gold;

                    It enters the Gold getter, which returns the value of ... the Gold getter. Which returns the value of ... the Gold getter. Which returns the value of ... the Gold getter. ... until the stack blows and your app crashes. The same happens when you try to use the setter: it infinitely recurses trying to set itself! Create a private backing field:

                    private int _Gold = 0;
                    public int Gold
                    {
                    get
                    {
                    return _Gold;
                    }

                    set
                        {
                        if (value == 20)
                            {
                            value += 5;
                            \_Gold = value;
                            }
                        }
                    }
                    

                    And it'll all work.

                    Sent from my Amstrad PC 1640 Never throw anything away, Griff Bad command or file name. Bad, bad command! Sit! Stay! Staaaay... AntiTwitter: @DalekDave is now a follower!

                    B Offline
                    B Offline
                    Brian_TheLion
                    wrote on last edited by
                    #9

                    Tbanks Griff. It looks like I've created a continuous loop. I'll try what you have suggested. I noticed that you used _Gold instead of Gold. Brian

                    P OriginalGriffO B 3 Replies Last reply
                    0
                    • B Brian_TheLion

                      Tbanks Griff. It looks like I've created a continuous loop. I'll try what you have suggested. I noticed that you used _Gold instead of Gold. Brian

                      P Offline
                      P Offline
                      Pete OHanlon
                      wrote on last edited by
                      #10

                      _Gold is a member variable. Gold is the property that exposes the variable. Basically, if you attempt to get a property and return the property name instead of a variable, you're going to repeatedly call the same getter. This is what causes the StackOverflowException.

                      This space for rent

                      B 1 Reply Last reply
                      0
                      • B Brian_TheLion

                        Tbanks Griff. It looks like I've created a continuous loop. I'll try what you have suggested. I noticed that you used _Gold instead of Gold. Brian

                        OriginalGriffO Offline
                        OriginalGriffO Offline
                        OriginalGriff
                        wrote on last edited by
                        #11

                        Not a continuous loop, but an "unbounded recursion" - similar thing, but the later will blow the stack at some point. Just to add to what Pete says, the naming conventions say that a backing field should have the same name as the property it is associated with, but prefixed with underscore:

                        private int _MyProperty;
                        public int MyProperty
                        {
                        get { return _MyProperty; }
                        set { _MyProperty = value; }
                        }

                        Sent from my Amstrad PC 1640 Never throw anything away, Griff Bad command or file name. Bad, bad command! Sit! Stay! Staaaay... AntiTwitter: @DalekDave is now a follower!

                        "I have no idea what I did, but I'm taking full credit for it." - ThisOldTony
                        "Common sense is so rare these days, it should be classified as a super power" - Random T-shirt

                        B 1 Reply Last reply
                        0
                        • B Brian_TheLion

                          I normally have an error message popup that tells me e exactly what is wrong (in most cases it's a spelling mistake) but this time this did not happen. I have stepped through programs to see how they work. I could try doing that but I suspect all that would happen is the same message would pop up which does not tell me exactly what is wrong. However a popup box with same message is better than nothing. I may need to research this message on the internet Brian

                          L Offline
                          L Offline
                          lmoelleb
                          wrote on last edited by
                          #12

                          Rule number 2 when troubleshooting (rule number one is "use the debugger") is not to assume anything. Assuming your debugger won't show you what is wrong is not the right approach. What would happen if you had spend 10 seconds setting a breakpoint in the getter and setter and then kept pressing F11: You would see your code repeatedly call itself, while the callstack keeps growing one line each time it calls itself.

                          1 Reply Last reply
                          0
                          • OriginalGriffO OriginalGriff

                            Not a continuous loop, but an "unbounded recursion" - similar thing, but the later will blow the stack at some point. Just to add to what Pete says, the naming conventions say that a backing field should have the same name as the property it is associated with, but prefixed with underscore:

                            private int _MyProperty;
                            public int MyProperty
                            {
                            get { return _MyProperty; }
                            set { _MyProperty = value; }
                            }

                            Sent from my Amstrad PC 1640 Never throw anything away, Griff Bad command or file name. Bad, bad command! Sit! Stay! Staaaay... AntiTwitter: @DalekDave is now a follower!

                            B Offline
                            B Offline
                            BillWoodruff
                            wrote on last edited by
                            #13

                            I twitch when I see a private backing field that has an uppercase letter following an initial underscore : :wtf: I'm sorry. However, when I consider this example is still current in the MS docs [^]:

                            public enum Color {...}
                            public class Control {
                            public Color Color { get {...} set {...} }
                            }

                            I throw up. Remember the daze when common practice was to use: _mSomeName ?

                            «Where is the Life we have lost in living? Where is the wisdom we have lost in knowledge? Where is the knowledge we have lost in information?» T. S. Elliot

                            1 Reply Last reply
                            0
                            • B Brian_TheLion

                              I can't see the reason why this does not work. There is no clear indication what the error is.

                              public int CurrentHitPoints { get; set; }
                              public int MaximumHitPoints { get; set; }
                              public int Gold
                              {
                              get
                              {
                              return Gold;
                              }

                                      set
                                      {
                                          if (value == 20)
                                         {
                                            value += 5;
                                            Gold = value;
                                         }
                                      }
                                  }
                                  public int ExperiencePoints { get; set; }
                                  public int Level { get; set; }
                              

                              Brian

                              L Offline
                              L Offline
                              Lost User
                              wrote on last edited by
                              #14

                              [Using Properties - C# Programming Guide | Microsoft Docs](https://docs.microsoft.com/en-us/dotnet/csharp/programming-guide/classes-and-structs/using-properties)

                              The Master said, 'Am I indeed possessed of knowledge? I am not knowing. But if a mean person, who appears quite empty-like, ask anything of me, I set it forth from one end to the other, and exhaust it.' ― Confucian Analects

                              B 1 Reply Last reply
                              0
                              • L lmoelleb

                                Your highest priority should be to learn to use the debugger. It might sound advanced... but it isn't. You will be able to spot the course of errors like this in seconds - even without a heap of experience. Sure some errors will still be tricky... but if they are tricky with a debugger, they are pretty much impossible to solve without. All you have to do is set a break point in the code you see a problem with (F9 in Visual Studio default key binding). Start the program with the debugger attached (F5) and reproduce the problem. Now you can step through the program line by line (F10/F11)- and you can see the values of all variables and fields at each line in the program. Spotting the setter calling itself is trivial this way. As a beginner you might still want to ask help on how to solve a problem once you identified it - but at least you can ask a much more precise question when you know what the error is - and get help a lot easier. So please - take the time to learn the debugger. The half hour will come back with interest of a few million percent.

                                K Offline
                                K Offline
                                kalberts
                                wrote on last edited by
                                #15

                                Seriously: Are there really people out there NOT using a debugger when developing code? To me that is like climbing Mt.Everest blindfolded, all on your own. There may be extreme exceptions where no traditional debugger is available or can't be used, e.g. in a certain class of embedded systems where the code is in flash memory and cannot be modified on a byte or word basis, so you can't poke debug interrupts. Or the processor is so primitive that it doesn't provide interrupts, or doesn't give sufficient external access to the address bus to run a probe on the outside. But those are very special cases. And I have never seen a system where you cannot do "printf style" debugging by setting output signals - even 8-bit embedded processors offer that (otherwise, how would they control what they are supposed to control?) Those special cases are lightyears away from desktop development in C#. If you run a company, you most certainly can affort the investment in, say, Visual Studio. For hobby programming, there is a free version providing so near-100% functionality that you probably won't notice the difference. (There are some differences, but they are rarely relevant for hobby programming.) Even printf debugging can work well in some cases (sometimes it is usesful as a companion to the interactive debugger, e.g. to traverse data structures and print selected values if this requires more processing than a simple watch expression). But "debugging by cranial massage", as one University lecturer phrased it. is not sufficient.

                                L B 2 Replies Last reply
                                0
                                • B Brian_TheLion

                                  I normally have an error message popup that tells me e exactly what is wrong (in most cases it's a spelling mistake) but this time this did not happen. I have stepped through programs to see how they work. I could try doing that but I suspect all that would happen is the same message would pop up which does not tell me exactly what is wrong. However a popup box with same message is better than nothing. I may need to research this message on the internet Brian

                                  M Offline
                                  M Offline
                                  Member 13566383
                                  wrote on last edited by
                                  #16

                                  Error messages which tell you about spelling mistakes or other syntax errors are generated at compile time of your program. No executable is produced and therefore your program doesn't run. A stack overflow condition can only occur when your program has been compiled and started running. The debugger is the tool to be used for analyzing run time errors. You should learn to understand the difference between these to error types.

                                  1 Reply Last reply
                                  0
                                  • K kalberts

                                    Seriously: Are there really people out there NOT using a debugger when developing code? To me that is like climbing Mt.Everest blindfolded, all on your own. There may be extreme exceptions where no traditional debugger is available or can't be used, e.g. in a certain class of embedded systems where the code is in flash memory and cannot be modified on a byte or word basis, so you can't poke debug interrupts. Or the processor is so primitive that it doesn't provide interrupts, or doesn't give sufficient external access to the address bus to run a probe on the outside. But those are very special cases. And I have never seen a system where you cannot do "printf style" debugging by setting output signals - even 8-bit embedded processors offer that (otherwise, how would they control what they are supposed to control?) Those special cases are lightyears away from desktop development in C#. If you run a company, you most certainly can affort the investment in, say, Visual Studio. For hobby programming, there is a free version providing so near-100% functionality that you probably won't notice the difference. (There are some differences, but they are rarely relevant for hobby programming.) Even printf debugging can work well in some cases (sometimes it is usesful as a companion to the interactive debugger, e.g. to traverse data structures and print selected values if this requires more processing than a simple watch expression). But "debugging by cranial massage", as one University lecturer phrased it. is not sufficient.

                                    L Offline
                                    L Offline
                                    Lost User
                                    wrote on last edited by
                                    #17

                                    Sadly yes. The number of QA posts that show the user has made no attempt to do even basic debugging, continues to amaze (and worry) me.

                                    1 Reply Last reply
                                    0
                                    • B Brian_TheLion

                                      I normally have an error message popup that tells me e exactly what is wrong (in most cases it's a spelling mistake) but this time this did not happen. I have stepped through programs to see how they work. I could try doing that but I suspect all that would happen is the same message would pop up which does not tell me exactly what is wrong. However a popup box with same message is better than nothing. I may need to research this message on the internet Brian

                                      D Offline
                                      D Offline
                                      Dave Kreskowiak
                                      wrote on last edited by
                                      #18

                                      There is no message you could possibly get that will tell you "exactly what is wrong" when the logic in your app is what is wrong. The error message you get can even be misleading. Using the debugger to step through the code is THE most powerful tool you can use to find problems, not error messages. Error messages are a symptom of the problem, not the solution to it.

                                      Asking questions is a skill CodeProject Forum Guidelines Google: C# How to debug code Seriously, go read these articles.
                                      Dave Kreskowiak

                                      B 1 Reply Last reply
                                      0
                                      • P Pete OHanlon

                                        _Gold is a member variable. Gold is the property that exposes the variable. Basically, if you attempt to get a property and return the property name instead of a variable, you're going to repeatedly call the same getter. This is what causes the StackOverflowException.

                                        This space for rent

                                        B Offline
                                        B Offline
                                        Brian_TheLion
                                        wrote on last edited by
                                        #19

                                        Hi Griff. Your change worked when there was a test for the value of 20 but when I changed the test value to 30 then 0 was displayed on the form for the amount of gold, then when I clicked on the Test button the gold value changed to 35. What I'm aiming at on this test is for 20 to first to appear on the form for the Gold value after the program is run, then when I press the Test button the gold value should change to 30 and in the test have 5 added to the 30 giving a gold value of 35. Here is my code On the main program I have SuperAdventure.cs

                                        public partial class SuperAdventure : Form { private Player _player; public SuperAdventure() { InitializeComponent(); Location location = new Location(1, "Home", "This is your house."); _player = new Player(10, 10, 20, 0, 1); Update(); } // TEST Button on Form private void btnTest_Click(object sender, EventArgs e) { _player.Gold = 30; Update(); } public void Update() { lblHitPoints.Text = _player.CurrentHitPoints.ToString(); lblGold.Text = _player.Gold.ToString(); lblExperience.Text = _player.ExperiencePoints.ToString(); lblLevel.Text = _player.Level.ToString(); } } } Player.cs code namespace Engine { public class Player { // This is needed for _player = new Player(10, 10, 20, 0, 1,); public int CurrentHitPoints { get; set; } public int MaximumHitPoints { get; set; } private int _Gold = 0; public int Gold { get { return _Gold; } set { if (value == 30) { value += 5; _Gold = value; } } } public int ExperiencePoints { get; set; } public int Level { get; set; } //In order to use lists – we need one variable or property to hold a collection of objects that are the same class public List Inventory { get; set; } public List Quests { get; set; } // This is needed for lblHitPoints.Text = _player.CurrentHitPoints.ToString() etc; public Player(int currentHitPoints, int maximumHitPoints, int gold,

                                        P 1 Reply Last reply
                                        0
                                        • K kalberts

                                          Seriously: Are there really people out there NOT using a debugger when developing code? To me that is like climbing Mt.Everest blindfolded, all on your own. There may be extreme exceptions where no traditional debugger is available or can't be used, e.g. in a certain class of embedded systems where the code is in flash memory and cannot be modified on a byte or word basis, so you can't poke debug interrupts. Or the processor is so primitive that it doesn't provide interrupts, or doesn't give sufficient external access to the address bus to run a probe on the outside. But those are very special cases. And I have never seen a system where you cannot do "printf style" debugging by setting output signals - even 8-bit embedded processors offer that (otherwise, how would they control what they are supposed to control?) Those special cases are lightyears away from desktop development in C#. If you run a company, you most certainly can affort the investment in, say, Visual Studio. For hobby programming, there is a free version providing so near-100% functionality that you probably won't notice the difference. (There are some differences, but they are rarely relevant for hobby programming.) Even printf debugging can work well in some cases (sometimes it is usesful as a companion to the interactive debugger, e.g. to traverse data structures and print selected values if this requires more processing than a simple watch expression). But "debugging by cranial massage", as one University lecturer phrased it. is not sufficient.

                                          B Offline
                                          B Offline
                                          Brian_TheLion
                                          wrote on last edited by
                                          #20

                                          But isn't the program debugging when it compiles. I normally get an error message if the compiler can't compile the code. Maybe your talking about some other debugging. Brian

                                          D 1 Reply Last reply
                                          0
                                          Reply
                                          • Reply as topic
                                          Log in to reply
                                          • Oldest to Newest
                                          • Newest to Oldest
                                          • Most Votes


                                          • Login

                                          • Don't have an account? Register

                                          • Login or register to search.
                                          • First post
                                            Last post
                                          0
                                          • Categories
                                          • Recent
                                          • Tags
                                          • Popular
                                          • World
                                          • Users
                                          • Groups