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; } }
It’s because you’re recursively calling the property – in the
setyou 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.
Alternatively, if you’re using C# 3.0, you could use an auto-property, which creates a hidden backing field for you, e.g.