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

Support init-accessor of properties #113

Open
Yeah69 opened this issue May 24, 2021 · 2 comments
Open

Support init-accessor of properties #113

Yeah69 opened this issue May 24, 2021 · 2 comments

Comments

@Yeah69
Copy link

Yeah69 commented May 24, 2021

Hi, I think it would be awesome if the C# 9.0 init-accessors for properties would be supported. Consider following example:

    public interface IRunnable
    {
        void Run();
    }

    internal class Runnable : IRunnable
    {
        internal IHelloWorldPrinter HelloWorldPrinter { private get; init; }

        public void Run() => HelloWorldPrinter.DoIt();
    }
    
    public interface IHelloWorldPrinter
    {
        void DoIt() => Console.WriteLine("Hello World!");
    }

    internal class HelloWorldPrinter : IHelloWorldPrinter
    {
    }

Without the init-accessor feature I would prefer construtor injection over property injection, because for the latter the property would need to become mutable. In my opinion the init-accessor is changing the game. In the example above, if constructor-injected, then the constructor would initialize a readonly field or get-only property anyway. So by supporting init-accessor the dependency could be injected into the "get-only" (of course there is also the init) property right away.

Additionally, that way the dependencies which are not relevant for the constructor but later on could be separated from the constructor.

One little caveat is of course that the init-injected properties cannot be used in the constructor, because they'll be initialized by the runtime after the constructor run through.

@YairHalberstadt
Copy link
Owner

YairHalberstadt commented May 24, 2021

In the future CSharp plans to support required properties. dotnet/csharplang#3630

Init properties can only be set at construction, but don't have to be set. Required properties have to be set at construction.

As such I think it makes more sense to wait for required properties and support them, than to support init properties.

We could view init properties as optional dependencies, i.e. - if we have something that can provide it then use that, otherwise ignore it, but I'm not sure if that would be best for users or not.

@Yeah69
Copy link
Author

Yeah69 commented May 25, 2021

Didn't know about this proposal. Considering that, you are right the required properties would be a better fit for what I suggested.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants