C# | Default Constructor

If you don’t provide a constructor for your class, C# creates one by default that instantiates the object and sets member variables to the default values as listed in the Default Values Table. Constructor without any parameters is called a default constructor. In other words, this type of constructor does not take parameters. The drawback of a default constructor is that every instance of the class will be initialized to the same values and it is not possible to initialize each instance of the class to different values.

The default constructor initializes:

  • All numeric fields in the class to zero.
  • All string and object fields to null.

Example 1:

filter_none

edit
close

play_arrow

link
brightness_4
code

// C# Program to illustrate the use
// of Default Constructor
using System;
  
namespace GFG {
      
class multiplication
{
    int a, b;
      
    // default Constructor
    public multiplication()   
    {
        a = 10;
        b = 5;
    }
  
// Main Method
public static void Main() {
      
    // an object is created, 
    // constructor is called
    multiplication obj = new multiplication(); 
      
    Console.WriteLine(obj.a);
    Console.WriteLine(obj.b);
      
    Console.WriteLine("The result of multiplication is: "
                                        +(obj.a * obj.b));
}
  
}
}

chevron_right


Output:

10
5
The result of multiplication is: 50

Example 2: In this example, the class Person does not have any constructors, in which case, a default constructor is automatically provided and the fields are initialized to their default values.

filter_none

edit
close

play_arrow

link
brightness_4
code

// C# Program to illustrate the use
// of Default Constructor
using System;
  
public class Person
{
    public int age;
    public string name;
}
  
  
// Driver Class
class TestPerson {
  
// Main Method
static void Main() {
  
    // object creation
    Person pers = new Person();
      
    Console.WriteLine("Name: {0}, Age: {1}", pers.name, pers.age);
  
}

chevron_right


Output:

Name: , Age: 0

Note: The output is so because a string is assigned to null by default and integers to 0.



My Personal Notes arrow_drop_up

Discovering ways to develop a plane for soaring career goals

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.




Article Tags :

1


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.