Defining "Constructor" in class

by Jagadish Pulakhandam on 12/10/2011 10:42:03 AM
Rated 0 from 0 votes
Brief: Demonstrates an example which explains the concept of "Constructor" in OOPS
Posted to: Basics of Object Oriented Programming in .NET
Add to DiggAdd to del.icio.usAdd to FURLAdd to RedditAdd to YahooAdd to BlinklistAdd to GoogleAdd to ma.gnoliaAdd to ShadowsAdd to Technorati

Constructor - A method which gets automatically executed when an instance is created.  Will not have any return type.  In C#, the name of the constructor should be the same as of class name.

Follow inline comments in the following example:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
 
namespace ConstructorDemo
{
    class Employee
    {
        public int Empno;
        public string Ename;
        public double Sal;
 
        //Constructor
        public Employee()
        {
            //This part gets executed automatically when an instance of this class is created
            //This part gets executed for every instance (and for that instance only)
  
            //The following does not make sense for this example.  But, just for this article
            Empno = 9999;
            Ename = "No Name yet";
        }
    }
}

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
 
namespace ConstructorDemo
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }
 
        private void button1_Click(object sender, EventArgs e)
        {
            Employee oEmp = new Employee(); //constructor gets executed here immediately after this statement
            MessageBox.Show(oEmp.Ename); //displays "No Name Yet"
            oEmp.Ename = "Jag";
            MessageBox.Show(oEmp.Ename); //displays "Jag"
        }
    }
}

Join the .NET Code Central Community and join the discussion!
Signing-up is FREE and quick. Do it now, we want to hear your opinion
0

Rated 0 from 0 votes ( login  to rate)
DotnetKicks DotnetKicksDe DotNetShoutout

Attachments / Source Code
You need to Login or Join for FREE to download the following