Simple class with default and overloaded constructor
This sample demonstrates use of default constructor, overloaded constructor, method and overloaded method in C#
Create new console C# console application.
Add the following code to Program.cs
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Text;
- namespace Classes_002
- {
- class Program
- {
- static void Main(string[] args)
- {
- // create new instance of the Calculate class
- Calculate calc1 = new Calculate();
- // call doCalculation method with the default Constructor
- Console.WriteLine(“default constructor: “ + calc1.doCalculation()+“\r”);
- // create another instance of the Calculate class
- Calculate calc2 = new Calculate(100);
- // call doCalculation method with the user variable passed to Constructor
- Console.WriteLine(“constructor that accepted user value: “ + calc2.doCalculation() + “\r”);
- // create another instance of the Calculate class
- Calculate calc3 = new Calculate();
- // call doCalculation method and pass to variables directly to method0
- Console.WriteLine(“method that accepts two double values: “ + calc2.doCalculation(25.35,10.12) + “\r”);
- Console.ReadKey();
- }
- }
- }
Add new class Calculate.cs with the following code
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Text;
- namespace Classes_002
- {
- class Calculate
- {
- // declare private variable for the class
- private int constantA;
- // declare initial value for default Constructor
- public Calculate()
- {
- constantA = 10;
- }
- // declare Constructor for input of user variable
- public Calculate(int a)
- {
- constantA = a;
- }
- // method that actually does the calculation
- public int doCalculation()
- {
- return constantA / 2;
- }
- public double doCalculation(double val1, double val2)
- {
- return val1*val2;
- }
- }
- }
This is a very simple example just to demonstrate how default and overloaded constructors work in C#.
Categories: C#, Code Snippets
