Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does Property Set throw StackOverflow exception?

Tags:

c#

I know java and would normally put in getter/setter methods. I am interested in doing it in C# with the following code, but it throws a StackOverflow exception. What am I doing wrong?

Calling Code

c.firstName = "a";

Property Code

public String firstName;
{
    get
    {
        return firstName;
    }
    set
    {
        firstName = value;
    }
}
like image 840
Adam Lerman Avatar asked Dec 15 '08 00:12

Adam Lerman


People also ask

What causes stackoverflow exception?

A StackOverflowException is thrown when the execution stack overflows because it contains too many nested method calls. using System; namespace temp { class Program { static void Main(string[] args) { Main(args); // Oops, this recursion won't stop. } } }

How do I fix stack overflow exception?

Setting the size of the stack or the maximum depth value of the recursion is allowed in most of the programming languages. Now that we have an opportunity to set the value of the depth of the stack, we have to set to a value as small as possible and observe the output.

Why do we get stack overflow exception in Java?

Class StackOverflowError Thrown when a stack overflow occurs because an application recurses too deeply.

Why stack overflow exception occurs in C#?

StackOverflowException is thrown for execution stack overflow errors, typically in case of a very deep or unbounded recursion. So make sure your code doesn't have an infinite loop or infinite recursion. StackOverflowException uses the HRESULT COR_E_STACKOVERFLOW, which has the value 0x800703E9.


2 Answers

It's because you're recursively calling the property - in the set you are setting the property again, which continues ad infinitum until you blow the stack.

You need a private backing field to hold the value, e.g.

private string firstName;  public string FirstName {     get     {         return this.firstName;     }     set     {         this.firstName = value;     } } 

Alternatively, if you're using C# 3.0, you could use an auto-property, which creates a hidden backing field for you, e.g.

public string FirstName { get; set; } 
like image 186
Greg Beech Avatar answered Oct 03 '22 06:10

Greg Beech


You are setting the property name inside your property--not the field name. This would work better:

private string m_firstName;  public String firstName; {     get     {         return m_firstName;     }     set     {         m_firstName = value;     } } 
like image 44
Michael Haren Avatar answered Oct 03 '22 05:10

Michael Haren