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.
- publicclass mcCalculator {
- privateint iOutVal;
-
- public mcCalculator() {
- iOutVal = 0;
- }
- public mcCalculator(int iVal1) {
- iOutVal = iVal1;
- }
-
- ~mcCalculator() {
- iOutVal = 0;
- }
-
- publicvoid displayiOutVal() {
- Console.WriteLine("iOutVal = {0}", iOutVal);
- }
-
- publicvoid add(int iVal1, int iVal2) {
- iOutVal = iVal1 + iVal2;
- }
-
- publicvoid subtract(int iVal1, int iVal2) {
- iOutVal = iVal1 - iVal2;
- }
-
- publicvoid Multiply(int iVal1, int iVal2) {
- iOutVal = iVal1 * iVal2;
- }
-
- publicvoid Devide(int iVal1, int iVal2) {
- iOutVal = iVal1 / iVal2;
- }
- }
Calling your class from Main
Now call mcCalculator from main. First create instance of mcCalculator and then call its member functions.
-
- class mcStart {
- publicstaticvoid Main() {
- mcCalculator mcCal = new mcCalculator(50);
- mcCal.add(12, 23);
- mcCal.displayiOutVal();
- mcCal.subtract(24, 4);
- mcCal.displayiOutVal();
- mcCal.Multiply(12, 3);
- mcCal.displayiOutVal();
- mcCal.Devide(8, 2);
- mcCal.displayiOutVal();
- }
- }
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.