#689 – References and Objects

A variable whose type is a reference type can be declared without making the variable point to an instance of that type (an object).  At this point, the value of the variable will be null.

A reference-typed variable can later be assigned to refer to an instance of the appropriate type, or it can be assigned at the point where it is declared.

            Dog myDog;
            myDog = new Dog("Kirby", 13);

            Dog yourDog = new Dog("Ruby", 2);

A reference-typed variable can be re-assigned to refer to a difference instance of the type.  (If an object is no longer referenced by any variables, it will eventually be garbage collected).

            Dog jack = new Dog("Jack", 15);
            Dog kirby = new Dog("Kirby", 13);

            Dog currentDog = jack;
            currentDog = kirby;

Notice also in this example that more than one reference-typed variable can refer to the same object.


About Sean
Software developer in the Twin Cities area, passionate about software development and sailing.

One Response to #689 – References and Objects

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

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 )

Connecting to %s

%d bloggers like this: