Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In C#, why you can set a property to its self [duplicate]

Accidentally I created a bug in my work. The cause of the bug is a snippet of c# code like

public ClassA{
        public string AProperty
        {
            get
            {
                return AProperty;
            }
            set
            {
                AProperty = value;
            }
        }
}

You can build that, and running that without any exceptions. But it will create an infinite loop. For example, while setting the AProperty, it always tries to assign the value to its self.

Anyone knows why in C# the compiler will allow this syntax?

like image 229
ValidfroM Avatar asked Apr 18 '13 18:04

ValidfroM


1 Answers

Because the C# compiler team didn't decide to make this exact case illegal. Possibly because they didn't consider the benefits of implementing it to be greater than the costs.

It's something that comes up with even the most trivial amount of testing; it's not a very subtle bug, and it's something that developers learn to look for if they get bitten by it a few times.

like image 93
Servy Avatar answered Oct 11 '22 14:10

Servy