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


  3. 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;
 
namespace constructor
{
    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;
 
namespace constructor
{
    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 this article will help to you.

0 comments


Leave a comment

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

Welcome to SQL Tutorials Point

Don't have an account? Click here to Create a new account, it takes less than a minute.