简体   繁体   中英

Returning value of static property from public instance property

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

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM