Level Extreme platform
Subscription
Corporate profile
Products & Services
Support
Legal
Français
Why I can not make my Connection String a const?
Message
 
 
To
23/09/2008 15:13:19
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:
01349998
Views:
31
>>>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 = "";
>>>
>>
>>What is better and why, the way I currently have it in util.cs or the way you showed?
>>
>> static readonly string ConnectionString = System.Configuration.ConfigurationManager.ConnectionStrings["FCCMSConnectionString"].ConnectionString;
>
>It all depends Naomi,
>If you are accessing something many times that is relatively stable (like a connection string) or has to be instantiate sometimes it is better use the property method above. The first time you access it the connection string will be determined and then set in the property. After that, you can just get it again and again. Of course it depends on if this class where you have the property stays around. If you make it static, that wouldn't be a problem. I have an application level class and I have some properties to get access to objects like this in there because I know they are always available and the objects are only instantiated once. The code below is also called Lazy Instantiation; it is a design pattern.
>
>
>public MyGpsClass Gps
>{
>     get
>     {
>          if (_myGpsClass == null)
>          {
>               _myGpsClass = new MyGpsClass();
>          }
>          return _myGpsClass;
>     }
>}
>private MyGpsClass _myGpsClass = null;
>
>This class isn't instantiated until it is need and after that the existing reference is passed instead of creating it again.
>
>Sorry if I went further than you needed for explanation.
>Tim

It is very interesting and important for me to understand. I believe the code you showed creates a singleton class.

In my case the class is static (util.cs) in App_Code directory and its methods are used in various places.
If it's not broken, fix it until it is.


My Blog
Previous
Next
Reply
Map
View

Click here to load this message in the networking platform