October 23, 2014
Hot Topics:
RSS RSS feed Download our iPhone app

ASP.NET Tip: Create a Smart Property to Instantiate Your Objects

  • May 26, 2006
  • By Eric Smith
  • Send Email »
  • More Articles »

When I'm writing Web applications, I may need to use lots of objects at various times while the application is running, but I generally don't always need all of them. Each object that gets instantiated takes system memory, and I try to keep my applications as small as possible for the best performance.

As a solution, I create "smart properties" to instantiate my objects. These properties allow me to keep a single instance of an object without worrying about whether the object has been instantiated yet. My code simply references the property, and the property figures out whether the object has been created yet or not.

Here's an example that manages a database connection:

private SqlConnection conn;
protected SqlConnection ActiveConnection
{
   get
   {
      if (conn == null)
      {
         conn = new SqlConnection("connectionstring");
         conn.Open();
      }
      return conn;
   }
}

The first time the ActiveConnection property is called, the conn object is null. It then is instantiated and opened using a connection string, which could be coming from the Web.config file or somewhere else. The SqlConnection object is kept for each subsequent call to the ActiveConnection property. The calling code simply references the ActiveConnection property instead of looking at the actual SqlConnection variable, thus eliminating the need to check whether the connection is open each time.

I use this type of property frequently with my BasePage class and take care of closing this or other similar objects in the Unload event of the page. That allows the connection to be released to the connection pool and used again later.

About the Author

Eric Smith is the owner of Northstar Computer Systems, a Web-hosting company based in Indianapolis, Indiana. He is also a MCT and MCSD who has been developing with .NET since 2001. In addition, he has written or contributed to 12 books covering .NET, ASP, and Visual Basic.






Comment and Contribute

 


(Maximum characters: 1200). You have characters left.

 

 


Sitemap | Contact Us

Rocket Fuel