Why doesn't the C# compiler stop properties from referring to themselves?

后端 未结 6 2096
灰色年华
灰色年华 2020-12-05 17:38

If I do this I get a System.StackOverflowException:

private string abc = \"\";
public string Abc
{
    get
    { 
        return Abc; // Note th         


        
6条回答
  •  一整个雨季
    2020-12-05 17:40

    Property referring to itself does not always lead to infinite recursion and stack overflow. For example, this works fine:

    int count = 0;
    public string Abc
    {
        count++;
        if (count < 1) return Abc;
        return "Foo";
    }
    

    Above is a dummy example, but I'm sure one could come up with useful recursive code that is similar. Compiler cannot determine if infinite recursion will happen (halting problem).

    Generating a warning in the simple case would be helpful.

提交回复
热议问题