tags:

views:

57

answers:

2

I was just playing around with some code in LINQPad and managed to crash the program with a stackoverflow exception.

I basically created a static property in a field and used a property to return the value from an instance.

The getter of my instance property would return the value of the static field, but the setter would set itself. When would this type of pattern be used and how come it generated a stackoverflow exception?

Code example of what I did:

void Main()
{
    SomeClass myinstance = new SomeClass();
    SomeClass.x = "Some Value";
    myinstance.y = "Some other value";
    myinstance.y.Dump();
}

public class SomeClass
{
    public static string x;

    public string y
    {
        get { return x; }
        set { y = value; }
    }
}
+4  A: 

This is the first thing I ever did with properties :) -- you're recursively calling the y setter rather than setting a backing field. Since it calls itself, it will eventually stackoverflow.

Each setter is syntactic sugar and is basically a method call. What you've done is basically equivalent to doing this with a method:

public class SomeClass
{
   public string GetValue() { return "some string"; }
   public void SetValue(string arg)
   { 
       SetValue(arg); // recursively calls itself until stackoverflow
   }
}
Mark Simpson
oh yes! Thanks Mark. What a rookie mistake :P
Jamie Dixon
Easy one to make... I'm sure a lot of people have done this :)
Mark Simpson
+1  A: 

You wrote y = value; instead of x = value; in the setter!

Note, that for simple properties you can use

public string y { get; set; }

Which will automatically generate a hidden field.

Danvil
Thanks Danvil. I didn't use an automatic property for this because I was testing what happens when you return the value of a static field from a non static property. :)
Jamie Dixon
I see, so my answer was somehow misdirected then :)
Danvil