Reputation: 33
I have a similar issue to this other post that I have class
public class MyClass
{
// other properties
public bool IsDefault { get; internal set; }
}
and I have a collection class defined like
public class MyCollection : ICollection<MyClass>
{
private List<MyClass> _itemList = new List<MyClass>();
public void SetAsDefault(MyClass item)
{
// Make sure no other items are default.
_itemList.ForEach(x => x.IsDefault = false);
// Set specified item as default.
_itemList.Find(x => x.Equals(item)).IsDefault = true;
}
}
I want to make sure that only that single item in MyCollection
is flagged as the default, while the same time being able to check directly on MyClass
whether a particular instance is the default. Marking the setter for MyClass.IsDefault
as internal
developers outside the assembly can't set IsDefault
. However, in my case, the developers I want to avoid faultily setting the IsDefault
property has access inside the assembly, so using internal
isn't enough.
Are there any clever solutions to this conundrum? I'm completely at a loss here...
Upvotes: 3
Views: 191
Reputation: 143
If you want to get or set instance that is default for specific collection you need property:
public MyClass Default { get; set; }
defined on MyCollection
class.
If you want to know whether given instance of MyClass
is default for specific collection you need method:
public bool IsDefaultFor(MyCollection collection) {
return collection.Default == this;
}
If you require default instance to be member of the collection, add such assertion in setter of Default
property and Remove
method.
Upvotes: 1
Reputation: 925
I think this is really hard to cleanly get right. Since every other developer could just set the Property somewhere else, I would try and turn the problem arround.
You could remove the Objects property and make it a property on the collection. Since someone can retrieve the MyClass instance and set it anyway, you could add a method to your MyCollection that checks wether a MyClass instance is the default in that collection.
Otherwise I don't see any good way to really forbid what you want.
Upvotes: 1