Home > C#, Code Snippets > Simple class with default and overloaded constructor

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

  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Text;
  5.  
  6. namespace Classes_002
  7. {
  8.     class Program
  9.     {
  10.         static void Main(string[] args)
  11.         {
  12.             // create new instance of the Calculate class
  13.             Calculate calc1 = new Calculate();
  14.  
  15.             // call doCalculation method with the default Constructor
  16.             Console.WriteLine(“default constructor: “ + calc1.doCalculation()+“\r”);
  17.  
  18.             // create another instance of the Calculate class
  19.             Calculate calc2 = new Calculate(100);
  20.             // call doCalculation method with the user variable passed to Constructor
  21.             Console.WriteLine(“constructor that accepted user value: “ + calc2.doCalculation() + “\r”);
  22.  
  23.             // create another instance of the Calculate class
  24.             Calculate calc3 = new Calculate();
  25.             // call doCalculation method and pass to variables directly to method0
  26.             Console.WriteLine(“method that accepts two double values: “ + calc2.doCalculation(25.35,10.12) + “\r”);
  27.             
  28.             Console.ReadKey();
  29.         }        
  30.     }
  31. }

 

Add new class Calculate.cs with the following code

  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Text;
  5.  
  6. namespace Classes_002
  7. {
  8.     class Calculate
  9.     {
  10.         // declare private variable for the class
  11.         private int constantA;
  12.  
  13.  
  14.         // declare initial value for default Constructor
  15.         public Calculate()
  16.         {
  17.             constantA = 10;
  18.         }
  19.  
  20.  
  21.         // declare Constructor for input of user variable
  22.         public Calculate(int a)
  23.         {
  24.             constantA = a;
  25.         }
  26.  
  27.         
  28.         // method that actually does the calculation
  29.         public int doCalculation()
  30.         {
  31.             return constantA / 2;
  32.         }
  33.  
  34.         public double doCalculation(double val1, double val2)
  35.         {
  36.             return val1*val2;
  37.         }
  38.  
  39.     }
  40.  
  41.  
  42.  
  43. }

 

This is a very simple example just to demonstrate how default and overloaded constructors work in C#.

Categories: C#, Code Snippets Tags:
  1. No comments yet.
  1. No trackbacks yet.

Spam Protection by WP-SpamFree