Information Technology Reference
In-Depth Information
The C# compiler creates a default constructor for your types whenever
you don't explicitly define any constructors.
Initializers are more than a convenient shortcut for statements in a con-
structor body. The statements generated by initializers are placed in object
code before the body of your constructors. Initializers execute before the
base class constructor for your type executes, and they are executed in the
order the variables are declared in your class.
Using initializers is the simplest way to avoid uninitialized variables in your
types, but it's not perfect. In three cases, you should not use the initializer
syntax. The first is when you are initializing the object to 0, or null. The
default system initialization sets everything to 0 for you before any of your
code executes. The system-generated 0 initialization is done at a very low
level using the CPU instructions to set the entire block of memory to 0.
Any extra 0 initialization on your part is superfluous. The C# compiler
dutifully adds the extra instructions to set memory to 0 again. It's not
wrong—it's just inefficient. In fact, when value types are involved, it's very
inefficient.
MyValType myVal1; // initialized to 0
MyValType myVal2 = new MyValType(); // also 0
Both statements initialize the variable to all 0s. The first does so by setting
the memory containing myVal1 to 0. The second uses the IL instruction
initobj, which causes both a box and an unbox operation on the myVal2
variable. This takes quite a bit of extra time (see Item 45).
The second inefficiency comes when you create multiple initializations for
the same object. You should use the initializer syntax only for variables
that receive the same initialization in all constructors. This version of
MyClass has a path that creates two different List objects as part of its
construction:
public class MyClass2
{
// declare the collection, and initialize it.
private List < string > labels = new List < string >();
MyClass2()
{
}
 
Search WWH ::




Custom Search