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

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
      if (conn == null)
         conn = new SqlConnection("connectionstring");
      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.

More by Author

Get the Free Newsletter!

Subscribe to Developer Insider for top news, trends & analysis

Must Read