Introduction
This article shows how to create a new class and call its member functions from Main progrmam. CalCulator is a class which has some member functions such as Square, Add, Subtract, Multiply etc.
using System;
/// <summary>
/// Summary description for Calculator.
/// </summary>
public class Calculator
{
// Square function
public int Square(int num)
{
return num * num;
}
// Add two integers and return the sum
public int Add(int num1, int num2)
{
return num1 + num2;
}
// Add two doubles and return the sum
public double Add(double num1, double num2)
{
return num1 + num2;
}
// Multiply two integers and return the result
public int Multiply(int num1, int num2)
{
return num1 * num2;
}
// Subtract the smaller number from the larger one
public int Subtract(int num1, int num2)
{
if (num1 > num2)
{
return num1 - num2;
}
return num2 - num1;
}
}
/// <summary>
/// This shows how to use Calculator class from the Main C# program.
/// </summary>
public class Program
{
static void Main()
{
Calculator calculator = new Calculator();
Console.WriteLine(calculator.Square(8).ToString());
Console.WriteLine(calculator.Add(8.3, 9.24).ToString());
Console.WriteLine(calculator.Multiply(5, 8).ToString());
Console.WriteLine(calculator.Subtract(22, 42).ToString());
}
}
Build and run the application.