Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 333
now he who must not be named. Avatar asked Jun 09 '26 21:06

now he who must not be named.


1 Answers

You're setting the singleton to null at the top of your get clause:

Rootpdf pdfConfiguration = null;
//THIS IS THE PROBLEM.

Note: 99% of the time, ReSharper is smarter than you. I don't like it, but it's true.

like image 128
It'sNotALie. Avatar answered Jun 11 '26 09:06

It'sNotALie.



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!