C# Dependency Injection – DI and Hypothetical Readonly Setters

cdependency-injection

Sometimes I would like to declare a property like this:

public string Name { get; readonly set; }

I am wondering if anyone sees a reason why such a syntax shouldn't exist. I believe that because it is a subset of "get; private set;", it could only make code more robust.

My feeling is that such setters would be extremely DI friendly, but of course I'm more interested in hearing your opinions than my own, so what do you think?

I am aware of 'public readonly' fields, but those are not interface friendly so I don't even consider them. That said, I don't mind if you bring them up into the discussion

Edit

I realize reading the comments that perhaps my idea is a little confusing. The ultimate purpose of this new syntax would be to have an automatic property syntax that specifies that the backing private field should be readonly. Basically declaring a property using my hypothetical syntax

public string Name { get; readonly set; }

would be interpreted by C# as:

private readonly string name;
public string Name
{
    get
    {
        return this.name;
    }
}

And the reason I say this would be DI friendly is because when we rely heavily on constructor injection, I believe it is good practice to declare our constructor injected fields as readonly.

Best Answer

The C# team has considered that this would be a very useful feature, and that's why in C# 6, they implemented it (just a little different from your proposal).

Getter-only auto-properties

This new kind of properties are getter-only, but can be set either inline or in the constructor. This means they are backed internally by a readonly field.

Instead of declaring a property as readonly set, you simply not declare it.

Inline assignment

public class Customer
{
    public string First { get; } = "Jane";
    public string Last { get; } = "Doe";
}

Constructor assignment

public class Customer
{
    public string Name { get; }
    public Customer(string first, string last)
    {
        Name = first + " " + last;
    }
}

You can read about this and other new features of C# 6 in the Roslyn wiki in GitHub.