Creating A Class And Calling It From Main Program

This article tells you how to create your own class with some function in it and how to call these functions from the main function.

Creating your class

This is how my class mcCalculator looks. Its has five functions besides constructor and destructor, called Add, Subtract, Devide (that was a spelling mistake), Multiply, and DisplayOutVal. As you can see from their names, these functions add, subtract, multiply, and divide and store the results in a private variable iOutVal which is called by DisplayOutVal to display the results.
  1. publicclass mcCalculator {  
  2.     privateint iOutVal;  
  3.     //Default constructor  
  4.     public mcCalculator() {  
  5.         iOutVal = 0;  
  6.     }  
  7.     public mcCalculator(int iVal1) {  
  8.             iOutVal = iVal1;  
  9.         }  
  10.         //destructor  
  11.         ~mcCalculator() {  
  12.             iOutVal = 0;  
  13.         }  
  14.     //methods  
  15.     publicvoid displayiOutVal() {  
  16.         Console.WriteLine("iOutVal = {0}", iOutVal);  
  17.     }  
  18.     // this function adds two values and saves in iOutVal  
  19.     publicvoid add(int iVal1, int iVal2) {  
  20.         iOutVal = iVal1 + iVal2;  
  21.     }  
  22.     // this function subtracts one from other and saves in iOutVal  
  23.     publicvoid subtract(int iVal1, int iVal2) {  
  24.         iOutVal = iVal1 - iVal2;  
  25.     }  
  26.     // this function multiplyies two values and saves in iOutVal  
  27.     publicvoid Multiply(int iVal1, int iVal2) {  
  28.         iOutVal = iVal1 * iVal2;  
  29.     }  
  30.     // this function devides one value from other and saves in iOutVal  
  31.     publicvoid Devide(int iVal1, int iVal2) {  
  32.         iOutVal = iVal1 / iVal2;  
  33.     }  
  34. }  
Calling your class from Main
 
Now call mcCalculator from main. First create instance of mcCalculator and then call its member functions.
  1. // Main Program   
  2. class mcStart {  
  3.     publicstaticvoid Main() {  
  4.         mcCalculator mcCal = new mcCalculator(50);  
  5.         mcCal.add(12, 23);  
  6.         mcCal.displayiOutVal();  
  7.         mcCal.subtract(24, 4);  
  8.         mcCal.displayiOutVal();  
  9.         mcCal.Multiply(12, 3);  
  10.         mcCal.displayiOutVal();  
  11.         mcCal.Devide(8, 2);  
  12.         mcCal.displayiOutVal();  
  13.     }  
  14. }  
Don't forget to call using System as the first line of your file.

Quick Method
 
Download the attached file, second.cs, and run from command line, csc second.cs.


Similar Articles
Mindcracker
Founded in 2003, Mindcracker is the authority in custom software development and innovation. We put best practices into action. We deliver solutions based on consumer and industry analysis.