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?
Asked
Active
Viewed 93 times
2
-
Was that property perhaps a delegate or event? – Adam Houldsworth Feb 19 '14 at 15:21
-
Are you talking about events? – Alberto Feb 19 '14 at 15:21
-
1I'm not sure, quite possibly. – PixelArtDragon Feb 19 '14 at 15:25
-
1Please don't. That is idiomatic for delegates but practically nothing else. – Eric Lippert Feb 19 '14 at 21:02
2 Answers
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