2

im writing a c# application. im pretty new to c#.

I got a StackOverflowException (yes! :D) trying to set the class properties in the constructor like this:

namespace WindowsUpdateOnLan
{
    public class NetworkAdapter
    {
        public NetworkAdapter(PropertyDataCollection properties)
        {
            String value = null;
            foreach (PropertyData pd in properties)
            {
                if (pd.Name.Equals("GUID"))
                    Id = Guid.Parse(pd.Value.ToString());

                if (pd.Name.Equals("Name"))
                    Name = pd.Value.ToString();

                if (pd.Name.Equals("NetConnectionID"))
                {
                    value = Regex.Replace(pd.Value.ToString(), @"\s+", "");
                    adapterType = (AdapterTypeEnum)Enum.Parse(typeof(AdapterTypeEnum), value);
                }

                if (pd.Name.Equals("NetEnabled"))
                {
                    value = Regex.Replace(pd.Value.ToString(), @"\s+", "");
                    adapterStatus = (AdapterStatusEnum)Enum.Parse(typeof(AdapterStatusEnum), value);
                }
            }
        }

        /// <summary>
        /// Contains the GUID that is used to identify the adapter
        /// </summary>
        public Guid Id
        {
            get { return this.Id; }
            private set { Id = value; }
        }

And Visual Studio tells me to make sure i dont have an infinite loop.

I must have forgotten something important or maybe the syntax is not right.

Could anybody take a look at it?

1
  • i was not asking about the exception so its no duplicate Commented Mar 18, 2016 at 20:21

1 Answer 1

10
public Guid Id
{
    get { return this.Id; }
    private set { Id = value; }
}

You call same property getter/setter in getter/setter. Thus recursion.

Solutions:

  1. Add field id and use it.
  2. Use autopropery: public Guid Id { get; private set; }
Sign up to request clarification or add additional context in comments.

2 Comments

thanks! autoproperty works awesome! its still not fully clear to me how this happens is it because i have no 'this.' in the setter?
@MikeAzazel doesn't matter. this is optional basically compiler adds it for you .

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.