Search code examples
c#design-patterns.net-4.0.net-4.5

Singleton pattern for a property in c#


I am trying to adapt singleton policy for my CsvConfiguration Property.

If the configuration is already available, just return the configuration. else, get the configuration and return the same and I am able to build this code.

    public Rootpdf pdfConfiguration
    {
        get
        {
            Rootpdf pdfConfiguration = null;
            try
            {
                if (pdfConfiguration == null)
                {
                    //retrieve the configuration file.
                    //load the configuration and return it!
                }
                else
                {
                    return pdfConfiguration;
                }
            }
            catch (Exception e)
            {
                Log.Error("An error occurred while reading the configuration file.", e);
            }

            return pdfConfiguration;
        }
    }

Advantages (i hope): Whenever my pdfConfiguration is wanted, if already it is available, i can return it. Need not load the configuration file eachtime and calculate the configuration.

My Query: The resharper! The resharper tells that the code

   if (pdfConfiguration == null) //The expression is always true.

Is it really a problem with resharper that it doesn't understand I am following this singleton pattern ?

or

Am I not following singleton pattern at all?


Solution

  • think you have to use a local variable out of the getter

        private static Rootpdf  _pdfConfiguration ;
        public static Rootpdf pdfConfiguration
        {
            get
            {
                try
                {
                    if (_pdfConfiguration == null)
                    {
                        //retrieve the configuration file.
                        //load the configuration and return it!
                    }
                    else
                    {
                        return _pdfConfiguration;
                    }
                }
                catch (Exception e)
                {
                    Log.Error("An error occurred while reading the configuration file.", e);
                }
    
                return _pdfConfiguration;
            }
        }
    

    and as you want a singleton, i made it a static property... hope it's what you need.