datkom datkom - 1 month ago 5
ASP.NET (C#) Question

Instanciate Interface to new Class C#

I'm reading WebHostBuilder.cs class.

It's not clear to me why

private readonly IHostingEnvironment _hostingEnvironment;


was instanciated in the constructor as
_hostingEnvironment = new HostingEnvironment();


Here is the (modified for succinctness) code:

public class WebHostBuilder
{
private readonly IHostingEnvironment _hostingEnvironment;

public WebHostBuilder()
{
_hostingEnvironment = new HostingEnvironment();
}
}


UPDATE

I found this question useful.
Cast interface to its concrete implementation object or vice versa?

Answer

I guess you´re confused that the value is set in the constructor instead where you declare the field. In your example you could easily and probably also validly write the following:

 private readonly IHostingEnvironment _hostingEnvironment = new HostingEnvironment();

This will have exactly the same effect, as it is implicitly converted to a constructor-statement by the compiler. So both are similar.

However there exists a need to use the constructor when you don´t know the value to be used at compile-time. Imagine the constructor of HostingEnvironment expects an integer to be passed:

public class WebHostBuilder
{
    private readonly IHostingEnvironment _hostingEnvironment // = new HostingEnvironment(whatToSetHere ???);

    public WebHostBuilder(int i)
    {
        _hostingEnvironment = new HostingEnvironment(i);
    }
}

During compile-time you don´t know the value to be provided for the HostingEnvironment-constructor. So you provide it as early as you get it, in this case in the constructor of your own class.

In addition the readonly-modifier simply states that you can set the value for a member only within the constructor (or in place with the declaration, which is converted to a constructor-call, remember what I´ve mentioned above).

Comments