2

I've seen certain .NET properties only allow adding and removing elements from a list through the += and -= operators. How do I create a property of a class with that functionality?

PixelArtDragon
  • 214
  • 2
  • 12

2 Answers2

1

If you are talking about Properties, there is no way how determine "syntax use" of your properties in following way:

  • Enable i += 1;
  • Disable i = i + 1;

You maybe mismatched it with "delegate and events" which uses syntax += for some operations. For more info about delegates and events you should look at http://msdn.microsoft.com/en-us/library/aa645739(v=vs.71).aspx for example.

EDIT: Last alternative I could think of is operator overloading but I haven't experience to refer about this specific situation so there is link with more info C# operator overload for `+=`? but I don't think so that this is exactly what are you looking for, because it will not put restriction on syntax usage of your properties

Community
  • 1
  • 1
Jaroslav Kadlec
  • 2,505
  • 4
  • 32
  • 43
0

You can achieve a similiar effect by doing:

    public class Test
    {
        private List<string> _myList;

        public Test()
        {
            _myList = new List<string>();
        }

        public List<string> MyList
        {
            get { return _myList; }
        }

        public void ManipulateList()
        {
            _myList.Add("string 1");
            _myList.Add("string 2");
        }
    }
Oberheim
  • 78
  • 11