Level Extreme platform
Subscription
Corporate profile
Products & Services
Support
Legal
Français
When to instantiate a class
Message
 
To
10/02/2009 12:07:51
General information
Forum:
ASP.NET
Category:
Other
Miscellaneous
Thread ID:
01380585
Message ID:
01380603
Views:
36
>I'm building a system in C#. My question is as follows:
>
>I open a form to enter work orders. I have a data class. I have a business rules class. I have a class that builds reports (to print work order). When is the best time to create an instance of each class? At the form startup or as needed in specific methods? If I start it at form startup then it is in memory for the life of the form. If I start it within a method, then it is my understanding garbage collection will clear it after the method goes out of scope.
>
>At the risk of hearing a lot of "it depends on....." comments, is one way better than the other?
>
>thanks
>
>Alan Wyne

My general rule of thumb is based on how often it's needed and/or how expensive it is to initialize. For something like a business object/rules class, it's probably going to be needed fairly often and from multiple places, so it gets created when the form inits (or lazy load it via a property - create it in the get if necessary). For something like a report, I would probably wait until it's needed.

If a var is used in a method it usually is cleared when it goes out of scope. Usually. It's really up to the garbage collector to determine when that really happens, though.

The other case is how expensive is it to init the class. If it does a lot of processing/grabbing data/etc. I will normally delay instanciation as long as possible, but then keep the object around after init (see my suggestion about using a lazy loaded property).

(by lazy loading, I mean this):
private MyBizObj m_bizObj;

public MyBizObj BizObj
{
   get
   {
      if (this.m_bizObj == null)
         this.m_bizObj = new MyBizObj();

      return this.m_bizObj;
   }
}
-Paul

RCS Solutions, Inc.
Blog
Twitter
Previous
Next
Reply
Map
View

Click here to load this message in the networking platform