C#: Assigning an instance

This entry is part 20 of 71 in the series C#

When we create an instance, some also called it instantiate an object, we can assign the instance to another instance.

For example, we create an instance using new operator:

Friend friend = new Friend();

We can assign the friend instance to a different instance name call pal.

using System;

namespace Hello
    class Friend
        private string name;
        private string major;

        private Friend()
            name = "John";
            major = "Biology";

        static void Main()
            Friend friend = new Friend();

            Console.WriteLine();  //This adds an empty new line

            Friend pal = friend;

            Console.WriteLine("How about pal?");


The line

Friend pal = friend

copies the value of friend to pal.

As a result, pal is now referencing the same Friend object as friend.

On the other hand, the following code creates two different Friend objects:

Friend friend = new Friend();
Friend pal = new Friend();


Series Navigation<< C#: Constructor
C#: Designing a class >>

Leave a comment

Leave a Reply