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?

Master Azazel
  • 612
  • 1
  • 12
  • 32

1 Answers1

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; }
Andrey
  • 59,039
  • 12
  • 119
  • 163
  • thanks! autoproperty works awesome! its still not fully clear to me how this happens is it because i have no 'this.' in the setter? – Master Azazel Mar 18 '16 at 20:26
  • @MikeAzazel doesn't matter. `this` is optional basically compiler adds it for you . – Andrey Mar 19 '16 at 13:26