Reputation: 12075
I'm trying to set up a class so that it's possible to initialize it using an object initializer, but it contains some collections. Ideally I'd like client code to be able to do:
MyClass myObj = new MyClass
{
Name = "Name",
Contents = new[]
{
"Item1",
"Item2"
}
}
However, where Contents
needs to be a BindingList<string>
. The underlying field stores a readonly reference to this list, and I'd like the setter to essentially do a Clear
followed by AddRange
to set the contents.
I can't make the Contents
property an IEnumerable<string>
, because client code wouldn't see the Add
method, among many others, at least not without casting it first. I can't make it a BindingList<string>
because if I set it, I need to construct a new binding list to pass to it.. this might be possible but I'd rather not introduce the inefficiency of construct a new BindingList<string>
solely for the purpose of passing it to the property setter.
The ideal thing to be able to do would be to have the getter return a BindingList<string>
and the setter accept IEnumerable<string>
, but C# doesn't allow getters/setters on a property to have different types.
Oh, and implicitly casting between BindingList<string>
and IEnumerable<string>
is a no-no, so I can't do that either (Link).
Is there any way around this?
Upvotes: 2
Views: 318
Reputation: 4867
I would recommed encapsulating the BindingList. In this situation go back to the old school way of creating objects so that you aren't creating unnecessary couplings. Favor good OO over language conventions.
Upvotes: 0
Reputation: 283893
C# initializer syntax will automatically call the Add
method on your property's collection object. That won't call Reset()
beforehand of course, but the object is still empty at that point, so it doesn't matter.
Does replacing the list have to use property set syntax? Having a setter replace the content of a collection without actually changing the collection object identity is very unexpected and will likely lead to bugs.
Upvotes: 2
Reputation: 5543
Create a custom collection class that derives from BindingList<string>
and add an implicit cast from type string[]
Upvotes: 1