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;
}
}
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. } } }
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.
Class StackOverflowError Thrown when a stack overflow occurs because an application recurses too deeply.
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.
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; }
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; } }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With