Introduction:

In this article we will explain how to use constructor or what is constructor in c# or how to use default constructor Or how to use Parameterized constructor in c# with example.

Description:

The constructor in C# has the same name as class or struct. the constructor is a method which is executed automatically at the time of object creation. It is used to initialize the data members of new object.

There can be two types of constructors in C#.

  1. 1. Default constructor
  2. 2. Parameterized constructor

C# Default Constructor

A constructor which has no parameter is known as default constructor. It is executed at the time of creating object.

C# Default Constructor Example: 

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
 
namespace SQLTutorialsPoint
{
    public class Customer
    {
        public Customer()
        {
            Console.WriteLine("Default Constructor executed");
        }
    }
    public class Program
    {
        public static void Main(string[] args)
        {
            Customer customer = new Customer();
            Console.ReadLine();
 
        }
    }
 
} 

Output:

Default Constructor executed

 

C# Parameterized Constructor

A constructor which has one or more parameters is called parameterized constructor. It is used to provide different values to objects or object members.

C# Parameterized Constructor Example:

 using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
 
namespace SQLTutorialsPoint
{
    public class Customer
    {
        public int id;
        public String name;
        public String Contact;
        public Customer(int i, String n, String c)
        {
            id = i;
            name = n;
            Contact = c;
        }
        public void display()
        {
            Console.WriteLine(id + "  " + name + "  " + Contact);
        }
    }
    public class Program
    {
        public static void Main(string[] args)
        {
            Customer customer = new Customer(101, "Manoj Kumar", "******7845");
            customer.display();
            Console.ReadLine();
 
        }
    }
}
 

OutPut:

101  Manoj Kumar  ******7845 

 

I hope ti will help to you after reading.

0 comments


Leave a comment

Make sure you enter the (*) required information where indicated. HTML code is not allowed.

you may also like