By 22/07/2015 12 Comments

Constructor In C#

  • The constructor in C# is a special type of method / function but unlike methods it has no return type even void.
  • It has the same name as its class name, a constructor is always declared as public access modifier because it is called from outside the class.
  • A constructor is used to initialize the instance variables, fields, an object, performs any task which creates a fully formed object OR it causes the initialization of require components for an object to be fully created. Here the word component means (fields, instance variables or any other class member etc. OR another words: It is the full responsibility of a constructor that it creates an object by giving require values to its attributes and behavior.
  • A constructor is called automatically when we create an object of a class OR It is automatically called after new operator at the time of an object creation.
  • A class can contains more than one or multiple constructors.
  • Like methods one or more parameters (local variables) can be passed in a constructor which is called parametrized constructor. If no parameter is passed in constructor that is called: a construct with an empty parameter-list.
  • All classes have a constructors by default, if we do not define our custom/own constructor the C# compiler supplies a default constructor which sets to all class members or fields to its default values such as false to bool, null to reference types and 0 for int and decimal types.

General Syntax:

access-modifier ClassName (parameterList)
{
members
}

STATEMENT DESCRIPTION
access-modifier It must be specified as public as its access modifier.
ClassName The name of a class in which this constructor has been declared.
(parameterList) List of local variables (optional).
{ Starting scope of constructor.
members These can be instance fields or variables.
} Ending scope of constructor.

Example – 1, using a constructor with empty parameter-list in a Marksheet program:

using System;
namespace csharpBasic
{
    class MarkSheet
    {
        // Instance variables or fields declaration.
        public double AspMarks;
        public double JavascriptMarks;
        public static double TotalMarks = 200;

        /* Following is a declaration of a 
           constructor with empty parameter-list, 
           it initializes 2 fields or initialize a Mark sheet object with values.
        */
        public MarkSheet()
        {
            AspMarks = 80;
            JavascriptMarks = 70;
        }

        // Return type method declaration which returns obtain marks.
        public double GetObtainMarks()
        {
            return AspMarks + JavascriptMarks;
        }

        /* Return type parametrized method declaration which returns percentage of obtain marks */
        public double GetPercentage(double obtainMarks, double totalMarks)
        {
            return (obtainMarks / totalMarks) * 100.0;
        }
    }
    
    class Program
    {
        // Static main method void type declaration.
        static void Main(string[] args)
        {
            // A Mark sheet object is being created.
            MarkSheet markSheet = new MarkSheet();

            // Following stataments print subject's marks.
            Console.WriteLine("Asp.NET marks: {0}", markSheet.AspMarks);
            Console.WriteLine("JavaScript marks: {0}", markSheet.JavascriptMarks);

            /* Following statement gets obtain marks by 
               calling GetObtainMarks() method. */
            double obtainMarks = markSheet.GetObtainMarks();

            /* Following statements print total marks and obtain marks
               by access TotalMarks static field and obtainMarks variable. */
            Console.WriteLine("Total Marks: {0}", MarkSheet.TotalMarks);
            Console.WriteLine("Obtain marks: {0}", obtainMarks);

            /* Following statement gets the percentage of 
               obtain marks by calling GetPercentage() method. */
            Console.WriteLine("Pecentage: {0}", markSheet.GetPercentage(obtainMarks, MarkSheet.TotalMarks));

            Console.ReadKey();
        }
        /*
        The Output will be:
         
        Asp.NET marks: 80 
        JavaScript marks: 70
        Total Marks: 200
        Obtain marks: 150
        Pecentage: 75
       */
    }
}


Example Р2, using a parametrized constructor in a Marksheet program:

using System;
namespace csharpBasic
{
    class MarkSheet
    {
        // Instance variables or fields declaration.
        public double AspMarks;
        public double JavascriptMarks;
        public static double TotalMarks = 200;

        /* Following is a declaration of a parametrized constructor 
           with 2 parameters, it initializes 2 fields or initialize 
           a Mark sheet object with values. */
        public MarkSheet(double aspMarks, double javascriptMarks)
        {
            AspMarks = aspMarks;
            JavascriptMarks = javascriptMarks;
        }

        // Return type method declaration which returns obtain marks.
        public double GetObtainMarks()
        {
            return AspMarks + JavascriptMarks;
        }

        /* Return type parametrized method declaration which returns percentage of obtain marks */
        public double GetPercentage(double obtainMarks, double totalMarks)
        {
            return (obtainMarks / totalMarks) * 100.0;
        }
    }
    
    class Program
    {
        // Static main method void type declaration.
        static void Main(string[] args)
        {
            /* A Mark sheet object is being created and
               it is passing 2 arguments to constructor.*/
            MarkSheet markSheet = new MarkSheet(80,70);

            // Following stataments print subject's marks.
            Console.WriteLine("Asp.NET marks: {0}", markSheet.AspMarks);
            Console.WriteLine("JavaScript marks: {0}", markSheet.JavascriptMarks);

            /* Following statement gets obtain marks by 
               calling GetObtainMarks() method. */
            double obtainMarks = markSheet.GetObtainMarks();

            /* Following statements print total marks and obtain marks
               by access TotalMarks static field and obtainMarks variable. */
            Console.WriteLine("Total Marks: {0}", MarkSheet.TotalMarks);
            Console.WriteLine("Obtain marks: {0}", obtainMarks);

            /* Following statement gets the percentage of 
               obtain marks by calling GetPercentage() method. */
            Console.WriteLine("Pecentage: {0}", markSheet.GetPercentage(obtainMarks, MarkSheet.TotalMarks));

            Console.ReadKey();
        }
        /*
        The Output will be:
         
        Asp.NET marks: 80 
        JavaScript marks: 70
        Total Marks: 200
        Obtain marks: 150
        Pecentage: 75
       */
    }
}





Next Tutorial →



Posted in: C# Basics, C#.NET

Leave your valuable Comment

Have a natural attraction for women cosmetics and replica watches uk clothes, no
more than two for men the most attractive one, is to make their own driving experience, happy and can serve as the facade of the car, another is to highlight the taste edify sentiment rolex replica watch. The replica rolex is undoubtedly the most fashionable accessories, wear a suit to attend the activities, but also get a decent match on the replica watches .