In this example, we create a class called Calculator and include a method that performs addition. Also, explanations are added for each section:
Using System
Adds the System library, which is necessary to use basic system functions in C#. For example, it allows you to use the Console class to get console output.
Calculator Class
Created to perform mathematical operations.
Add Method:
public int Add(int a, int b) takes two integer (int) parameters and adds them.
The expression return a + b; returns the sum of the variables a and b.
Program Class
Main Method:
This is where the program starts running. It is considered the starting point of a program in C#.
Calculator calculator = new Calculator(); creates an object of the Calculator class.
The expression int result = calculator.Add(5, 3); calls the Add method to calculate the sum of 5 and 3 and assigns the result to the result variable.
Console.WriteLine($“Result: {result}”); prints the calculated result to the console. The $ sign allows us to print the variable directly by string interpolation.
This example shows the process of creating a class in C#, defining methods and using those methods to perform a simple calculation.