This article is based on the original article that was previously written using older version of Visual Studio. You can find the original article on the given below link:
This article shows how to create a new class and call its member functions from Main program. Calculator is a class which has some member functions such as square, add, subtract, multiply, division etc.
ClassLibrary:
- We can create a class library (in other words DLL file) of code containing classes and methods.
- One DLL file can be used in many applications in .NET like Console Application, Windows Application and Web Application and so on.
- To use a DLL file in an application we need to add a reference to the DLL file.
- DLL is not a self-executable file instead it is to be shared by many applications for code reusability purposes.
Procedure to Create a Class Library:
- Start a new project in Visual Studio from the New Project dialogue box, select Class Library Template from the Project Template Window.
- In the Name box, type a name for your Class Library. Then click OK.
- When you click OK, it will create a namespace with the name we gave for the Library and you will see the following in the code window:
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Text;
- using System.Threading.Tasks;
-
- namespace ClassLibrary1
- {
- public class CalCulator {}
- }
See the file Class1.cs in the Solution Explorer as given below:
Now add the following methods to the Calculator to do arithmetic operations (Square, Addition, Subtraction, Multiplication and Division).
We've added five simple methods; one for Square, second for addition, third for subtraction, fourth for multiplication, and fifth for Division. Similarly, we can add more methods to CalCulator for other operations.
- public class CalCulator
- {
-
- public int Square(intnum)
- {
- returnnum * num;
- }
-
- public int Add(int num1, int num2)
- {
- return num1 + num2;
- }
-
-
- public int Multiply(int num1, int num2)
- {
- return num1 * num2;
- }
-
- public int Subtract(int num1, int num2)
- {
- if (num1 > num2)
- {
- return num1 - num2;
- }
-
- return num2 - num1;
-
- }
-
- public float Division(float num1, float num2)
- {
- return num1 / num2;
- }
-
- }
This shows how to use
CalCulator class from Main C# program:
- using ClassLibrary1;
-
- namespace ConsoleApplication2
- {
- class Program
- {
- static void Main(string[] args)
- {
- {
- CalCulator sq = new CalCulator();
- Console.WriteLine(sq.Square(12));
- Console.WriteLine(sq.Add(8, 63));
- Console.WriteLine(sq.Multiply(5, 8));
- Console.WriteLine(sq.Subtract(10, 42));
- Console.WriteLine(sq.Division(3, 4));
- Console.ReadLine();
- }
- }
- }
- }
Output:
To read other articles on the Calculator, please click on the following references link: