1

How do you initialise a class using the C#12 primary construtor syntax. I know how to do it using dependency injection but cant find any docs showing how to do it with a normal class.

here is what I want to change to the primary constructor syntax.

internal class AutoHttpClient : IAutoHttpClient
{
    private readonly HttpClient httpClient;

    public AutoHttpClient()
    {
        httpClient = new HttpClient();
    }

}

im guessing that just doing the below will not work or will it?

internal class AutoHttpClient(HttpClient httpClient) : IAutoHttpClient
{
}

I have also looked onlint but all the examples aside of DI were using base types like int etc. Thanks for the help.

8
  • 1
    You will need to keep the field and initialise it: class AutoHttpClient(HttpClient httpClient): IAutoHttpClient { readonly HttpClient httpClient = httpClient; } Commented Feb 28, 2024 at 17:03
  • 1
    You didn't have the client as a ctor argument to begin with. Why do you now? If you want an exact equivalent: that's not it. Commented Feb 28, 2024 at 17:10
  • 1
    Sorry but...what is exactly your question? What are you trying to achieve and where are you failing at? Commented Feb 28, 2024 at 17:10
  • 1
    Yes. What are you trying to achieve and where are you stuck? Because I find it confusing. You have the first version, trying to convert it to c# 12 primary constructor syntax version? Or what Commented Feb 28, 2024 at 17:30
  • 1
    With the 2nd version: its still just a constructor. Besides did you try writing it yourself? I did and it works. Commented Feb 28, 2024 at 17:45

1 Answer 1

2

Your second example works just fine:

internal class AutoHttpClient(HttpClient httpClient)
{
    public async Task SendRequestAsync()
    {
        await httpClient.GetAsync("url");
    }
}

Note that in this case httpClient is basically a closed-over variable, and not a named private readonly field. If you want to prevent the internal code from changing the value of httpClient after construction, you'll need to declare a separate field. But you can still initialize it from the primary constructor's parameter.

internal class AutoHttpClient(HttpClient httpClient)
{
    private readonly HttpClient httpClient = httpClient;
    public async Task SendRequestAsync()
    {
        await httpClient.GetAsync("url");
    }
}

In this case, the field overrides the variable name httpClient, so the compiler doesn't make the closure field available in your methods: only in the field initializers. So when the method references httpClient it's referencing the declared field instead.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.