Total Pageviews

Thursday, August 9, 2012

Constructors

C# supports the use of
class constructors
, which allow the state of an object to be
established at the time of creation. A constructor is a special method of a class that is called indirectly
when creating an object using the
new keyword. However, unlike a “normal” method,
constructors never have a return value (not even
void) and are always named identically to theclass they are constructing.

Every C# class is provided with a freebee
default constructor that you may redefine if need be. By
definition, a default constructor never takes arguments. Beyond allocating the new object into
memory, the default constructor ensures that all field data is set to an appropriate default value

Defining Custom Constructors
Typically, classes define additional constructors beyond the default. In doing so, you provide the
object user with a simple and consistent way to initialize the state of an object directly at the time
of creation

However, as soon as you define a custom constructor, the default constructor is
silently removed
from the class and is no longer available! Think of it this way: if you do not define a custom constructor,
the C# compiler grants you a default in order to allow the object user to allocate an
instance of your type with field data set to the correct default values. However, when you define
a unique constructor, the compiler assumes you have taken matters into your own hands.

No comments:

Post a Comment