C#: Constructor

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

Constructors of a class will initialize the data members of the new object.

In the following example, a class named Friend is defined by using a simple constructor.

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

This class is then instantiated with the new operator.  As in the line below, friend is now an instance of the Friend class.

Friend friend = new Friend();

The Friend constructor is invoked by the new operator immediately after the above line is executed and memory is allocated for the new object.

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(friend.name);
            Console.WriteLine(friend.major);
            Console.ReadLine();
        }
    }
}

argument

Note that I have declared the 2 member types and the constructor as private as there is only one Friend class and they all belong to the same class.

Normally, we would pass variables into the constructor to initialize the values.

Constructor with parameters
using System;

namespace Constructor
{
    class Friend
    {      
        private string name;
        private string major;
 
        private Friend(string name1, string major1)
        {
            name = name1 ;
            major = major1;
        }
 
        static void Main()
        {
            string name = "John";
            string major = "Major";

            Friend friend = new Friend(name, major);
            Console.WriteLine(friend.name);
            Console.WriteLine(friend.major);
            Console.ReadLine();
        }  
    }  
}

argument1

 

Series Navigation<< C#: The core ideas of Object-Oriented Programs
C#: Assigning an instance >>