ConstructorsDestructors.md - brainchildservices/curriculum GitHub Wiki

Slide 1

Constructors and Destructors

C# Constructors:
A constructor is a special method of the class that gets automatically invoked whenever an instance of the class is created.
The advantage of a constructor is that it is called when an object of a class is created. It can be used to set initial values for fields.
Constructor helps with saving time as we don't have to initialize fields separately and reduce the code.

Example:
Case1: We are creating a class Car without constructor and initializing the fields one by one after creating the object
https://dotnetfiddle.net/Ip33bM

Slide 2

Case1: In the second case, we will call the constructor and pass the value to fields so that we don't need to take the pain to initialize fields one by one.
https://dotnetfiddle.net/frgY6B

Constructor syntax
A constructor is a method whose name is the same as the name of its class. Its method signature includes only the method name and its parameter list; it does not include a return type.

Even if we don't explicitly create a constructor for a class, the compiler will automatically create a default constructor of the class. The default constructor initializes all numeric fields in the class to zero and all string and object fields to null.
Case1: Compiler created default constructor
Eg: https://dotnetfiddle.net/SnZzOX
Case2: Manually created default constructor
Eg: https://dotnetfiddle.net/Hm6hW4

Slide 3

Default Constructor in C#
A constructor which has no argument is known as the default constructor. It is invoked at the time of creating object.
Things inside the default constructor gets executed when the object is created.
All numeric fields in the class are initialized to zero and all string and object fields to null.
https://dotnetfiddle.net/Hm6hW4

Parameterized Constructor in C#
A constructor with at least one parameter is called a parameterized constructor. The advantage of a parameterized constructor is that you can initialize each instance of the class with a different value.
Eg: Case where there is only constructor
https://dotnetfiddle.net/JEIMeX

Slide 4

Eg: Case where more than one constructor exists. The constructors differ in the parameter list.
https://dotnetfiddle.net/t7tUwM

  • Error:'Car' does not contain a constructor that takes 0 arguments
    If we create a parameter constructor, the default constructor is not created by the compiler at run time.
    https://dotnetfiddle.net/7op0hx
    To fix the issue, we would need to create an explicit default constructor
    https://dotnetfiddle.net/kryRnS

Constructor Overloading in C#
It is the ability to redefine a Constructor in more than one form.
We can overload constructors in different ways as follows:

  1. By using different type of arguments
  2. By using different number of arguments
  3. By using different order of arguments

https://dotnetfiddle.net/CHREsq

Slide 5

  • Q1 When a class constructor gets called?
    When we create an object of the class.

  • Q2 If you create 5 objects of a class, then how many time constructors will be called?
    Constructor will be called 5 times on creating 5 objects of the class. On every object creation a constructor gets called.

  • Q3 When you write a constructor, what return type do you write in constructor declaration?
    No need to write a return type in a constructor declaration.

  • Q4 Why do you use constructor?
    Constructor is used to initialize the class fields (class member variables) with default values / initial values.

Slide 6

Exercise:

  • Q1: Write a constructor in the Car class given below that initializes the brand field with the string โ€œFordโ€.
    Call the getBrand() method in the Main method of the Program class and store the value of the brand in a variable, and print the variable.
    https://dotnetfiddle.net/9HDqr6

  • Q2: Add a constructor to your Animal class. Your constructor should pass in two string parameters named "name" and "sound". Call the Speak method in Main method.
    https://dotnetfiddle.net/1j9iae

Slide 7

C# Destructors:
The Destructor is also a special type of method present in a class, just like a constructor, having the same name as the class name but prefix with ~ tilde. The destructor in C# gets executed when the object of the class is destroyed.

The object of a class in C# will be destroyed by the garbage collector in any of the following cases

  • Case1: At the end of a program execution each and every object that is associated with the program will be destroyed by the garbage collector.

  • Case2: The Implicit calling of the garbage collector occurs sometime in the middle of the program execution provided the memory is full so that the garbage collector will identify unused objects of the program and destroys them.

  • Case 3: The Explicit calling of the garbage collector can be done in the middle of program execution with the help of the โ€œGC.Collect()โ€ statement so that if there are any unused objects associated with the program will be destroyed in the middle of the program execution.

https://dotnetfiddle.net/NhoXo3

Slide 8

What is Garbage Collection?
Automatic memory management is made possible by Garbage Collection in .NET Framework. When a class object is created at runtime, certain memory space is allocated to it in the heap memory. However, after all the actions related to the object are completed in the program, the memory space allocated to it is a waste as it cannot be used. In this case, garbage collection is very useful as it automatically releases the memory space after it is no longer required.

References: https://www.javatpoint.com/c-sharp-constructor
https://www.c-sharpcorner.com/UploadFile/0c1bb2/constructors-and-its-types-in-C-Sharp/
https://www.geeksforgeeks.org/c-sharp-constructors/#:~:text=A%20constructor%20with%20no%20parameters,to%20null%20inside%20a%20class.
https://docs.microsoft.com/en-us/dotnet/csharp/programming-guide/classes-and-structs/constructors
https://dotnetcademy.net/Learn/2039/Pages/12
https://www.w3schools.com/cs/cs_constructors.asp
https://www.interviewsansar.com/c-exercise-on-constructor-with-solution/

https://dotnettutorials.net/lesson/destructor-csharp/
https://www.tutorialspoint.com/What-are-destructors-in-Chash-programs
https://www.javatpoint.com/c-sharp-destructor

https://www.geeksforgeeks.org/garbage-collection-in-c-sharp-dot-net-framework/