Mark As Completed Discussion

Working with Object-Oriented Libraries

When working with C#, you will often find yourself using object-oriented libraries to accomplish common tasks. Object-oriented libraries are pre-built collections of reusable code components that follow the principles of object-oriented programming.

One common use case of object-oriented libraries is performing mathematical calculations. C# provides the System.Math class in the .NET Framework, which includes various methods for mathematical operations such as addition, subtraction, multiplication, and division.

However, you can also create your own custom object-oriented libraries to encapsulate specific functionality or business logic. These libraries can be reused across multiple projects, enhancing code reusability and maintainability.

Here's an example of a custom math helper library in C#:

TEXT/X-CSHARP
1using System;
2
3public class MathHelper
4{
5    public static double Add(double num1, double num2)
6    {
7        return num1 + num2;
8    }
9
10    public static double Subtract(double num1, double num2)
11    {
12        return num1 - num2;
13    }
14
15    public static double Multiply(double num1, double num2)
16    {
17        return num1 * num2;
18    }
19
20    public static double Divide(double num1, double num2)
21    {
22        if (num2 == 0)
23        {
24            throw new ArgumentException("Cannot divide by zero.");
25        }
26        return num1 / num2;
27    }
28}
29
30public class Program
31{
32    public static void Main()
33    {
34        double num1 = 10;
35        double num2 = 5;
36
37        double sum = MathHelper.Add(num1, num2);
38        Console.WriteLine(sum);
39
40        double difference = MathHelper.Subtract(num1, num2);
41        Console.WriteLine(difference);
42
43        double product = MathHelper.Multiply(num1, num2);
44        Console.WriteLine(product);
45
46        double quotient = MathHelper.Divide(num1, num2);
47        Console.WriteLine(quotient);
48    }
49}
CSHARP
OUTPUT
:001 > Cmd/Ctrl-Enter to run, Cmd/Ctrl-/ to comment