A public constructor is created when the class needs to be accessed from anywhere in the program. A public
function is needed when we need to use the function outside the class anywhere in the program. Whenever an object of the class is created outside the class in the program, a public constructor is called.
A public constructor in C# is created through the following syntax:
class class_name{public class_name (arguments){// any code for the public constructor// for the class}}
class_name
: These are the names of the class in the program.
In the next line, we define the public constructor using the public
keyword followed by the same name with which we defined the class.
Inside the constructor function, we will write the code that needs to be executed whenever the constructor is called.
arguments
: These are optional and, if they are mentioned, it's called a parameterized constructor.
The public constructor is a void function that executes the code written inside the constructor. Nothing is returned here. Whenever the object is created, the code is executed.
Let's discuss an example to understand the concept of a public constructor in C#.
class Vehicle{public Vehicle(){System.Console.WriteLine("This is the line inside the public constructor.");}static void Main(){Vehicle car = new Vehicle();}}
The above code is an example of a public constructor in C#. A class name Vehicle
is created. After that, we write a public constructor with the same name and, inside that function, we write the code that needs to be executed. In the main function, we create the object named car
Vehicle class using the command new Vehicle()
. Whenever the code is executed, the output will be the code written inside the public constructor.
Free Resources