Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Are set-only properties bad practice? [duplicate]

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 
    }
}
like image 950
kelloti Avatar asked Dec 30 '10 17:12

kelloti


People also ask

Why we use write only property in C#?

A write only property is a property that we can assign a value to but can't get that value because that property doesn't have a get accessor. For example we have a Person class that has the property FirstName that has a set accessor but doesn't have a get accessor so it is a write only property.

How can you make a property write only?

You can use WriteOnly only at module level. This means the declaration context for a WriteOnly property must be a class, structure, or module, and cannot be a source file, namespace, or procedure. You can declare a property as WriteOnly , but not a variable.

What is read only property in C sharp?

In a field declaration, readonly indicates that assignment to the field can only occur as part of the declaration or in a constructor in the same class. A readonly field can be assigned and reassigned multiple times within the field declaration and constructor.

Can a field be public?

Fields can be marked as public, private, protected, internal, protected internal, or private protected. These access modifiers define how users of the type can access the fields. For more information, see Access Modifiers. A field can optionally be declared static.


2 Answers

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; }
    }
}
like image 56
Dan Tao Avatar answered Nov 03 '22 21:11

Dan Tao


It could be useful for Dependency Injection, where instead of using a constructor for the injection you are using properties.

like image 25
Aaron McIver Avatar answered Nov 03 '22 22:11

Aaron McIver