André Fiedler
André Fiedler

Reputation: 1103

Implementing interface properties in interfaces with a setter?

This Question explains how to implement interface properties in interfaces: Implementing interface properties in interfaces?

Now how do I implement a Setter with this? I'm getting "Cannot convert source type ..."

Is this the right way?

class WpfReportParams : IReportParams
{
    private ObservableCollection<StatusEnum> _selectedStatuses;

    public WpfReportParams()
    {
        _selectedStatuses = new ObservableCollection<StatusEnum>();
    }

    public IEnumerable<StatusEnum> SelectedStatuses
    {
        get { return _selectedStatuses; }
        set
        {
            var collection = value as ObservableCollection<StatusEnum>;
            if (collection != null)
            {
                _selectedStatuses = collection;
            }
        }
    }
}

Upvotes: 0

Views: 298

Answers (2)

default
default

Reputation: 11635

No, that would not be the correct way. You shouldn't have setters to Collections. If you need to add to your collection, implement an Add method or expose your property via IList<T> or ICollection<T> or a similar interface which supports the Add method instead.

Note that this can be accomplished using explicit implementations of the interface, where you are able to expose a different collection than that from the interface.

public interface IReportParams {
    IEnumerable<StatusEnum> SelectedStatuses { get; }
}

public class WpfReportParams : IReportParams {
    private readonly ObservableCollection<StatusEnum> _SelectedStatuses;

    public WpfReportParams() {
        _SelectedStatuses = new ObservableCollection<StatusEnum>();
    }

    public ICollection<StatusEnum> SelectedStatuses {
        get { return _SelectedStatuses; }
    }

    IEnumerable<StatusEnum> IReportParams.SelectedStatuses {
        get { return SelectedStatuses; }
    }
}

This is a better solution, considering that if you would have a setter and overwrite the value of the current collection, all event handlers for the current collection would be lost (or at least not trigger when new StatusEnum were added to the collection).

If you do need to "reset" your collection, use Clear() instead.

Upvotes: 1

Nikhil Agrawal
Nikhil Agrawal

Reputation: 48568

Is this the right way?

Yes. Its the right way.

Where are you stuck?

Note: Collections do not have set part. Only get part. In its get part we initialize backup-field if it is null and always access property and not backup-field. Like this

private IEnumerable<StatusEnum> _selectedStatuses;

public IEnumerable<StatusEnum> SelectedStatuses
{
    get 
    {
        if (_selectedStatuses == null)
            _selectedStatuses = new List<StatusEnum>();

        return _selectedStatuses; 
    }        
}    

Upvotes: 0

Related Questions