1
\$\begingroup\$

I wanted a pattern to manage web.config appsettings. I want to be able to have a default setting if the config setting was missing. I also wanted the check for the value in the config file to happen only once, not each time the the value is retrieved.

Public NotInheritable Class ExternalReportRequestBL

    ''' <summary>
    ''' The default value for max number of request attempts
    ''' </summary>
    ''' <remarks></remarks>
    Private Shared _ReportRequestMaxExecuteAttemptDefault As Integer

    Shared Sub New()
        If Not Integer.TryParse(ConfigurationManager.AppSettings("ReportRequestMaxExecuteAttempt"), ExternalReportRequestBL._ReportRequestMaxExecuteAttemptDefault) Then
            _ReportRequestMaxExecuteAttemptDefault = 10
        End If
    End Sub

    Friend Shared ReadOnly Property MaxNumberOfTries As Integer
        Get
            Return ExternalReportRequestBL._ReportRequestMaxExecuteAttemptDefault
        End Get
    End Property
End Class

Now, I can access the variable from anywhere in the assembly:

ExternalReportRequestBL.MaxNumberOfTries

What are your thoughts?

\$\endgroup\$
1
  • \$\begingroup\$ May I ask what lend you to wanting this? Typically, those settings are specifically for specifying defaults and configuration settings. I'm smelling an XY problem, but I don't yet understand what your real problem is. \$\endgroup\$
    – RubberDuck
    May 15 '16 at 13:58
1
\$\begingroup\$

Integer.TryParse will overwrite the value of that shared property with 0 if the value is not there. Use something like this instead:

Shared Sub New()
    Dim parsed As Integer
    If Integer.TryParse(ConfigurationManager.AppSettings("ReportRequestMaxExecuteAttempt"), parsed) Then
        _ReportRequestMaxExecuteAttemptDefault = parsed
    End If
End Sub
\$\endgroup\$
1
  • \$\begingroup\$ You are correct. Changed my question accordingly. \$\endgroup\$
    – Shai Cohen
    Apr 26 '12 at 23:47

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.