Why does Property Set throw StackOverflow exception?

后端 未结 2 800
小蘑菇
小蘑菇 2020-11-22 03:27

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 do

2条回答
  •  清歌不尽
    2020-11-22 03:37

    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; }
    

提交回复
热议问题