Tuesday, June 29, 2010

C# tip - 6/29/2010

Initializing private variables in a class is good.  This practice will allow the object to never have nulls and not having to deal with NullPointerExceptions.  However, there are three reasons why you should not initialize the attributes:

  • initializing VALUE TYPES to NULL or 0 is redundant since these types are initialized to 0 at creation time.  
    • Int32 i; <== already initialized to 0.  
  • multiple initializations for the same object
public class Test
{
  private ArrayList t = new ArrayList();
  public Test(){}
  public Test(ArrayList l)
  {
    t = l;
  }
}
    • in this scenario, the ArrayList's initialization in the attribute is overriden by the initialization in the second constructor.  It's like initializing the same variable twice.  The following example is a better solution:
public class Test
{
  private ArrayList t;
  public Test()
  {
    Test(new ArrayList());
  }
  public Test(ArrayList l)
  {
    t = l;
  }
}
  • exception handling is impossible on attribute initialization.  If exception handling is necessary, initialize the attribute in the constructor.
When initially instantiating a type, here's the order of operations:
  1. Static variable storage is set to 0
  2. Static variable initializers execute
  3. Static constructors for the base class execute
  4. Static constructor executes
  5. Instance variable is set to 0
  6. Instance variable is initialized
  7. Base class instance constructors execute (for a specific constructor overload)
  8. Instance constructor executes

No comments:

Labels