What Is a Constructors??
We can say that only use of constructors is to initialize the values whenever an object is called- Constructor is Basically a function
- But this function has a name same as that of class name
- Constructors has no return types
- The Constructor is called when the instance of the class that is the object is created.
- Program 1:
- Program 2:
- Program 3:
So Here goes the Program 1:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace constructors1
{
class check
{
int num1, num2,num3;
void initialize() //We are creating a function that will initialise the values
{
num1 = 20;
num2 = 30;
}
void add_nunmbers()
{
num3 = num1 + num2;
}
void display()
{
Console.WriteLine("The addition of the numbers 20 and 30 is {0}",num3);
}
static void Main(string[] args)
{
check c1=new check();
c1.initialize();//We are calling the function to initialize
c1.add_nunmbers();
c1.display();
Console.ReadLine();
}
}
}
Program 2:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace constructors1
{
class Constructor
{
int num1, num2, num3;
Constructor() //We are creating a function that has the name same as that of the class this will initialise the values
{
num1 = 20;
num2 = 30;
}
void add_nunmbers()
{
num3 = num1 + num2;
}
void display()
{
Console.WriteLine("The addition of the numbers 20 and 30 is {0}", num3);
}
static void Main(string[] args)
{
Constructor c1 = new Constructor();//This will automaitcally initialize the values
c1.add_nunmbers();
c1.display();
Console.ReadLine();
}
}
}
Program 3: Here we will be using inputs from the user.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace constructors1
{
class Constructor
{
int num1, num2, num3;
Constructor(int number1,int number2) //We are creating a constructor with parameter
{
num1 = number1;
num2 = number2;
}
void add_nunmbers()
{
num3 = num1 + num2;
}
void display()
{
Console.WriteLine("The addition of the numbers {0} and {1} is {2}",num1,num2, num3);
}
static void Main(string[] args)
{
Console.WriteLine("Enter Two Numbers to be Added");
int n1, n2;
n1 = Convert.ToInt32(Console.ReadLine());
n2 = Convert.ToInt32(Console.ReadLine());
Constructor c1 = new Constructor(n1,n2);//caling the constructors with parameters
c1.add_nunmbers();
c1.display();
Console.ReadLine();
}
}
}
No comments:
Post a Comment