Object Oriented Programming

Constructor in C#

A constructor is a special method that builds the object when a new object is created.


Syntax
modifier className (dataType parameter1, dataType parameterN) { 
   //initalizations of class fields in terms of defined parameters. 
} 

Notes

The name of the constructor must be the same as the name of the class.

Constructors are not considered members of a class and is called automatically when a new instance of an object is created.

A constructor is used to initialize fields defined by the class.


Example
public class Scores {
    string name;
    int score;
    ///constructor
    public Scores (string studentName, int examMark) { 
       name = studentName; 
       score = examMark; 
    }
}

Add to Slack

< Static Methods   |   Instantiation >

© 2018 SyntaxDB. All Rights Reserved.