#41 – Instantiating Reference Types Using the new Keyword

To create an object of a particular type, you need to instantiate the type.  Value types are instantiated by assigning them a value.  Reference types are instantiated using the new keyword.  Using new allows us to create a new instance of the type.

When new is used to instantiate a type, the type’s constructor is called to perform the initialization.  The type may have a default constructor that takes no parameters, or it may have a constructor that takes one or more parameter values.  It may also support multiple constructors.

Variables declared as instances of reference types will hold the value null until they are instantiated.

 Person p1;     // Not instantiated, value is null

 // p2 points to new instance of the Person class
 //   Default constructor, takes no parameters
 Person p2 = new Person();

 // Construct another Person object using a
 //   different constructor, which takes Name and Age
 Person p3 = new Person("Sean", 46);
Advertisements

About Sean
Software developer in the Twin Cities area, passionate about .NET technologies. Equally passionate about my own personal projects related to family history and preservation of family stories and photos.

3 Responses to #41 – Instantiating Reference Types Using the new Keyword

  1. Pingback: #921 – Objects Are Explicitly Created but Automatically Destroyed | 2,000 Things You Should Know About C#

  2. Pingback: #926 – How Memory Is Allocated for Objects on the Managed Heap | 2,000 Things You Should Know About C#

  3. Sheriff says:

    Nice post! Sean
    Thanks

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: