Level Extreme platform
Subscription
Corporate profile
Products & Services
Support
Legal
Français
Why I can not make my Connection String a const?
Message
From
23/09/2008 14:50:16
Timothy Bryan
Sharpline Consultants
Conroe, Texas, United States
 
General information
Forum:
ASP.NET
Category:
Coding, syntax and commands
Environment versions
Environment:
C# 3.0
OS:
Windows XP
Network:
Windows 2003 Server
Database:
MS SQL Server
Miscellaneous
Thread ID:
01349894
Message ID:
01349985
Views:
24
This message has been marked as a message which has helped to the initial question of the thread.
>>>Hi everybody,
>>>
>>>I was thinking that instead of accessing my connection string through configuration manager in several procedures of our global static class I'll make it a const property. So, based on another existing const I put
>>>
>>>   private const string TelephoneRegex = @"(1\s*[-\/\.]?)?(\((\d{3})\)|(\d{3}))\s*[-\/\.]?\s*(\d{3})\s*[-\/\.]?\s*(\d{4})\s*(([xX]|[eE][xX][tT]| )\.?\s*(\d+))*";
>>>    private const string ConnectionString = System.Configuration.ConfigurationManager.ConnectionStrings["FCCMSConnectionString"].ConnectionString;
>>>
>>>
>>>at the very top of the class.
>>>
>>>However, I'm getting this error
>>>
>>>Error 1 'Util.ConnectionString' is of type 'string.' A const of reference type other than string can only be initialized with null
>>>
>>>Do you know if this is a wrong approach? What can I do to use this as a property?
>>>
>>
>>If you mark something as "const" the compiler has to be able to resolve it at compile time (not runtime). That's why it's not working. You could expose it via a property with a get only - read it into a member on first access. Then it's read-only (if that's really your goal) and you're not having to read from the web.config on each access.
>
>I tried to remove the word const and got a new error Error 1 'Util.ConnectionString': cannot declare instance members in a static class
>
>I guess I would put it back to all places where it was used. Or may be you can give me some code sample?
>
>Thanks again.

Paul gave you a great suggestion, here is some code to do that. This is seperate from your static v instance issue. This way it is only in one place and retrieved only the first time it is accessed.
public string ConnString
{
     get
     {
          if (_connString == "")
          {
               _connString = System.Configuration.ConfigurationManager.ConnectionStrings["FCCMSConnectionString"].ConnectionString;
          }
          return _connString;
     }
}
private string _connString = "";
Timothy Bryan
Previous
Next
Reply
Map
View

Click here to load this message in the networking platform