CodeGuru Home VC++ / MFC / C++ .NET / C# Visual Basic VB Forums Developer.com
Results 1 to 3 of 3
  1. #1
    Join Date
    Apr 2009
    Posts
    4

    System.StackOverflowException errors?

    I get some "System.StackOverflowException was unhandled" by running the following C# code, I don't understand why.
    Code:
        class Test
        {
            static void Main(string[] args)
            {
                Customer cust = new Customer();
                cust.ID = 1;
                cust.Name = "Parrot";
                Console.WriteLine("ID: {0}, Name: {1}", cust.ID, cust.Name);
            }
        }
    
        class Customer
        {
            public int ID { get; set; }
    
            public string Name
            {
                get { return this.Name; }
                set { this.Name = value.ToUpper(); }
            }
        }

  2. #2
    Join Date
    Mar 2005
    Location
    Vienna, Austria
    Posts
    4,538

    Re: System.StackOverflowException errors?

    Code:
        class Customer
        {
            public int ID { get; set; }
     
            public string Name
            {
                get { return this.Name; }
                set { this.Name = value.ToUpper(); }
            }
        }
    The red (bold Italic) ones create an infinite loop. If you try to read the Nameproperty it wants to read the this.Name which again is an attempt to read the name property. You need to do
    Code:
        class Customer
        {
            private string _name;
     
            public int ID { get; set; }
     
            public string Name
            {
                get { return _name; }
                set { _name = value.ToUpper(); }
            }
        }
    Uppercase, lowercase is very necessary in C# !!
    Last edited by JonnyPoet; April 13th, 2009 at 03:03 PM.
    Jonny Poet

    To be Alive is depending on the willingsness to help others and also to permit others to help you. So lets be alive. !
    Using Code Tags makes the difference: Code is easier to read, so its easier to help. Do it like this: [CODE] Put Your Code here [/code]
    If anyone felt he has got help, show it in rating the post.
    Also dont forget to set a post which is fully answered to 'resolved'. For more details look to FAQ's about Forum Usage. BTW I'm using Framework 3.5 and you ?
    My latest articles :
    Creating a Dockable Panel-Controlmanager Using C#, Part 1 | Part 2 | Part 3 | Part 4 | Part 5 | Part 6 | Part 7

  3. #3
    Join Date
    Apr 2009
    Posts
    4

    Re: System.StackOverflowException errors?

    Thanks!

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  





Click Here to Expand Forum to Full Width

Featured