04 Feb C# Constructors
A Constructor in C# has the same name as the class name. Constructor gets called automatically when we create an object of a class. It does not have a return value. In this lesson, we will learn what are Constructors with examples and how to set parameters.
We have discussed the following topics:
- How to create a Constructor
- Constructor Parameters
How to create a Constructor
To create a Constructor in C#, the same class name is used followed by parentheses. Let’s say the class name is Studyopedia, therefore the Constructor would be the following:
1 2 3 4 5 |
Studyopedia() { // Constructor // Code comes here } |
Let us see an example to create a Constructor in C#:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 |
using System; namespace Demo { class Rectangle { // Constructor name is the same as the class name Rectangle() { Console.WriteLine("The Constructor!!"); Console.WriteLine("A rectangle has 4 sides, 4 corners, and 4 right angles"); } static void Main(string[] args) { /* Constructor gets called automatically when we create an object of a class */ Rectangle rct = new Rectangle(); } } } |
Output
1 2 3 4 |
The Constructor!! A rectangle has 4 sides, 4 corners, and 4 right angles |
Constructor Parameters
Parameterized Constructor is a constructor with a particular number of parameters. This is useful if you have different objects and you want to provide different values.
Let us see an example of a parameterized constructor with 2 parameters:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 |
using System; namespace Demo { // Create a Rectangle class class Rectangle { double length; double width; // Constructor name is the same as the class name // Constructor Parameters Rectangle(double len, double wid) { length = len; width = wid; } static void Main(string[] args) { /* Constructor gets called automatically when we create an object of a class */ Rectangle rct1 = new Rectangle(5, 10); Rectangle rct2 = new Rectangle(7, 15); // Display Console.WriteLine("Area of Rectangle1"); Console.WriteLine("Length = "+rct1.length+", Width = "+rct1.width); Console.WriteLine("\nArea of Rectangle2"); Console.WriteLine("Length = "+rct2.length+", Width = "+rct2.width); } } } |
Output
1 2 3 4 5 6 7 |
Area of Rectangle1 Length = 5, Width = 10 Area of Rectangle2 Length = 7, Width = 15 |
No Comments