Wednesday, July 23, 2014

CLR via C# - CHAPTER 8 Methods

Methods
Instance Constructors and Classes (Reference Types)

When constructing a reference type object, the memory allocated for the object is always zeroed out before the type’s instance constructor is called. Any fields that the constructor doesn’t explicitly overwrite are guaranteed to have a value of 0or null.

If you define a class that does not explicitly define any constructors, the C# compiler defines a default (parameterless) constructor for you whose implementation simply calls the base class’s parameterless constructor.

Instance Constructors and Structures (Value Types)

Value types don’t actually even need to have a constructor defined within them, and the C# compiler doesn't emit default parameterless constructors for value types.

The CLR does allow you to define constructors on value types. The only way that these constructors will execute is if you write code to explicitly call one of them,

The trick part is that C# doesn’t allow a value type to define a parameterless constructor.

As an alternative way to initialize all the fields of a value type, you can actually do the following.
// C# allows value types to have constructors that take parameters.
public SomeValType(Int32 x) {
// Looks strange but compiles fine and initializes all fields to 0/null.
this = new SomeValType();
m_x = x; // Overwrite m_x's 0 with x
// Notice that m_y was initialized to 0.
}
In a value type’s constructor, thisrepresents an instance of the value type itself and you can actually assign to it the result of newing up an instance of the value type, which really just zeroes out all the fields.

Type Constructors
If a type has a type constructor, it can have no more than one. In addition, type constructors never have parameters.

Because the CLR guarantees that a type constructor executes only once per AppDomain and is thread-safe, a type constructor is a great place to initialize any singleton objects required by the type.

In fact, because the CLR is responsible for calling type constructors, you should always avoid writing any code that requires type constructors to be called in a specific order.




















































No comments:

Post a Comment