I have a class called Attribute, which contains a list. I want the get method to return true/false if a given string is present in the list. However, I want the set method to accept a string and add it to the list.
I don’t have a compiler handy, but my code would more or less look like this. Is this possible to do?
class Attribute{
private list<string> m_data;
public bool this[string s] {
get { return this.m_data.Contains[s]; }
set { this.m_data.Add[s]; }
}
}
This works, but it’s horrendously counter-intuitive. Assignments to your property (which is actually an indexer) would have to contain some kind of Boolean value, which gets ignored and thrown away:
So yes, you can do this. But it’s a bad idea, because no one maintaining the code will have a clue what’s going on. That dangling Boolean looks like it has some kind of meaning, but it doesn’t; it violates the Principle of Least Astonishment when assigning true does the same thing as assigning false! Not to mention, the value you pass in as an “index” really isn’t an index into anything at all. It’s legal, but using syntax in a completely different way from what it’s intended for.
In all honesty you’d be better served just accessing the
List<string>directly and calling its existingContains()andAdd()methods.