Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Best practice when assigning a collection reference to a property

Tags:

c#

properties

I'm heavily geared towards C++ thinking and need some guidance on a specific C# matter. Let's assume we have the following class:

public class Foo
{
    private IList<Bar> _bars = new List<Bar>(); // Note IList<> vs List<>.

    public IList<Bar> Bars
    {
        get { return _bars; }
        set
        {
            ...
        }
    }
}

Now, in place of the ..., I'm leaning towards clearing _bars and AddRange the items from the set argument value, instead of just assigning value to _bars. The way I see it, is that I want to keep referencing the same items that the value items references, not the actual IList<Bar> that value references.

Is that wrong thinking on my side? How do you think here?

Edit: After some comments, I realized I must add that I want to be able to use an existing collection of Bars in the Foo ctor and initialize _bars from that collection. So, with that revision and the comments so far, this feels better:

public class Foo
{
    private readonly List<Bar> _bars = new List<Bar>();

    public Foo(IEnumerable<Bar> bars)
    {
        _bars.AddRange(bars);
    }

    public IList<Bar> Bars
    {
        get { return _bars; }
    }
}

Is it better?

like image 585
Johann Gerell Avatar asked Dec 13 '25 20:12

Johann Gerell


2 Answers

If we're talking about business (domain) objects, I expose IEnumerable<T> and whatever methods are appropriate for the collection, typically Add, Remove, and Clear. I almost never expose a setter for a collection.

like image 165
Jamie Ide Avatar answered Dec 15 '25 08:12

Jamie Ide


Is it necessary to be able to make the Bars property of your instance of Foo refer to another List ?

If not, then I would prefer not to have a property-setter for Bars.

If it is necessary to be able to set the Bars property to another List instance, then I think I would find it strange to find that your setter modifies the list. I mean: when I assign another List of Bars to that property, I would assume that my instance of Foo then contains the Bars that were available in the list that I've assigned to that property. No more, no less. I would find it strange to find out that suddenly the collection contains more (or less) Bars...

like image 39
Frederik Gheysels Avatar answered Dec 15 '25 08:12

Frederik Gheysels



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!