Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Property assigned in constructor can use initializer instead #35

Open
rubberduck203 opened this issue May 16, 2015 · 3 comments
Open

Property assigned in constructor can use initializer instead #35

rubberduck203 opened this issue May 16, 2015 · 3 comments

Comments

@rubberduck203
Copy link
Contributor

Take advantage of C# 6.0's auto-property initializers.

  1. If a Property has a read-only backing field.
  2. If a Property has a private Setter, but is only set in the constructor.

The first case is a lot of (now) unnecessary code. The second is poor man's immutability (and not really all so immutable).

@Vannevelj
Copy link
Owner

The syntax for this feature is

public int MyProperty { get; set; } = 10;
public IList<int> MyProperty { get; } = new List<int>();

which provides a default value for the property. Note that this also works with a read-only property.

@rubberduck203
Copy link
Contributor Author

That's the point of (2). Out of laziness, many of us create immutable from the outside properties when we could make immutable from everywhere. I was thinking this should catch those situations. I'm trying to formalize a test case to clarify.

@rubberduck203
Copy link
Contributor Author

class Foo
{
     int SomeProp { get; private set; }

    Foo()
    {
        this.SomeProp = 100;
    }
}

Assume there are other members, but the only place this gets set is in the constructor. Then it could be rewritten like this.

class Foo
{
     int SomeProp { get; private set; } = 100;
}

@Vannevelj Vannevelj changed the title Read-only field can use Auto-Property Initializer instead Property assigned in constructor can use initializer instead Jun 3, 2015
@Vannevelj Vannevelj added this to the v1.9.0 milestone Aug 5, 2015
@Vannevelj Vannevelj modified the milestones: v2.0.0, v1.9.0 Aug 16, 2015
@Vannevelj Vannevelj modified the milestones: v2.0.0, v1.9.4 May 29, 2016
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

2 participants