Are set-only properties bad practice?

kelloti picture kelloti · Dec 30, 2010 · Viewed 15.7k times · Source

I have some C# code that loves to create properties that have setters but no getters. To me this seems like an anti-pattern, but am I missing something?

public List<SiteVisitSummary> DataSource {
    set {
        // crazy logic here 
    }
}

Answer

Dan Tao picture Dan Tao · Dec 30, 2010

I don't know if I'd call it an anti-pattern or not. I think the important thing to realize is that the property in your example is essentially a method, disguised as a property. For this reason it's unintuitive, and I'd generally avoid it. To me this looks a lot more natural:

public void SetDataSource(IEnumerable<SiteVisitSummary> dataSource)
{
    // crazy logic here
}

One fairly reasonable case I have seen made for set-only properties is when there are several properties grouped together such that setting all to a single value is a reasonable thing to do (but obviously, getting all as one value doesn't make sense). For example:

class Polyhedron
{
    public int Height { get; set; }
    public int Width { get; set; }
    public int Depth { get; set; }

    public int AllDimensions
    {
        set { Height = Width = Depth = value; }
    }
}