A class consists of the data, fields, and the methods. Let's take an example, and discuss the class and its members.
- class Student
- {
- //data of a class.
- string firstName;
- string lastName;
- //Constructor of class.
- public Student()
- {
- }
- //Method in the class.
- public void Print()
- {
- }
- //Destructor
- ~Student()
- {
- firstName = null;
- lastName = null;
- }
- }
- DataFields: string firstName and string lastName defines the datafields of Student class.
- public Student() {}
This defines the constructor of the class. Let's discuss constructors in detail.
Constructor has the same name as the class, as we have already seen in the example above. The class and constructor are both named Student.
The constructor can accept the parameters, as shown below.
- class Student
- {
- //data of a class.
- string firstName;
- string lastName;
- //Constructor of Student class with parameters.
- public Student(string fName, string lName)
- {
- }
- }
- class Student {
- //data of a class.
- string firstName;
- string lastName;
- //Constructor of Student class.
- public Student(string fName, string lName) {
- //Initialise in constuctor:
- firstName = fName;
- lastName = lName;
- //or we can use by using this keyword because this keyword acts as the instance of the current class.Lets see below:
- }
- }
- class Program {
- static void Main(string[] args) {
- Student student = new Student("Neha", "Jangra");
- }
- }
When we create an instance of class in the example above and run the program, then we can see by putting a breakpoint the constructor will be called at that point and values will be assigned to the data fields in the constructor only.
Please see the attached screenshot.




NehaPosted Jan 10, 2017, 10:56 PM
Thank you so much Gagan :)
gagandeep singhPosted Jan 9, 2017, 8:46 AM
This is what i was looking for ... thanks neha for this blog.
Sagar ChowdhuryPosted Jan 8, 2017, 2:46 PM
This is really a good explanation .
Jasbeer SinghPosted Jan 4, 2017, 7:25 AM
Welcome ............................................................
Jasbeer SinghPosted Jan 4, 2017, 7:06 AM
Nice one.................................................................