Miguel Moura
Miguel Moura

Reputation: 39384

Field ... is never assigned to, and will always have its default value null

I have the following HandleErrorModule class:

public sealed class HandleErrorModule : IHttpModule {
    private static ILogger _logger;
    private static CustomErrorsSection _section;
    private static Dictionary<HttpStatusCode, String> _views;

    private static CustomErrorsSection CustomErrorsSection { 
      get { 
        if (_section != null) 
          return _section;
        else 
          return WebConfigurationManager.GetWebApplicationSection("system.web/customErrors") as CustomErrorsSection; 
      } 
    }

    private static ILogger Logger { 
      get { return (_logger != null) ? _logger : ObjectFactory.GetInstance<ILogger>(); }
    }

    private static Dictionary<HttpStatusCode, String> Views { 
      get { 
        if (_views != null) 
          return _views;
        else
          return new Dictionary<HttpStatusCode, String> { { HttpStatusCode.NotFound, "NotFound_" }, { HttpStatusCode.InternalServerError, "Internal_" } }; 
       } 
    }

    public void Init(HttpApplication application) {

       // Handle error code.
       // Here I access CustomErrorsSection, Logger and Views properties

    }

In get the warning in:

Field 'HandleErrorModule._views' is never assigned to, and will always have its default value null Field 'HandleErrorModule._section' is never assigned to, and will always have its default value null Field 'HandleErrorModule._logger' is never assigned to, and will always have its default value null

What am I doing wrong?

Upvotes: 0

Views: 4399

Answers (2)

poke
poke

Reputation: 387715

I think you wanted those static properties to lazily initialize the objects. The way you did it though, they never set the private fields, but keep on creating new objects. So you probably wanted to do it like this instead:

private static Dictionary<HttpStatusCode, String> Views
{
    get
    {
        // when the private field is null, initialize the value
        if (_views == null)
        {
            _views = new Dictionary<HttpStatusCode, String> {
                    { HttpStatusCode.NotFound, "NotFound_" },
                    { HttpStatusCode.InternalServerError, "Internal_" } };
        }

        // and always return the private field
        return _views;
    } 
}

Upvotes: 1

danish
danish

Reputation: 5610

Pretty clear form the message. None of the members are assigned values anywhere. The properties where they are used are get only.

Looking the kind of code and presumed usage, I would suggest a parameterized constructor that can set values for these fields.

Upvotes: 3

Related Questions