Thursday, October 24, 2024

Example of computation as data in C#


"Computation as data" typically refers to treating computations or operations as data that can be manipulated, passed around, and executed dynamically within a program. This concept is often associated with functional programming paradigms. In C#, you can achieve this using delegates, anonymous functions, or lambdas. Here's an example demonstrating computation as data using a lambda function:

using System;

class Program
{
    // Define a delegate that represents a computation
    delegate int Computation(int a, int b);

    static void Main(string[] args)
    {
        // Example computation: addition
        Computation addition = (a, b) => a + b;

        // Example computation: multiplication
        Computation multiplication = (a, b) => a * b;

        // Perform computations using the defined functions
        int result1 = PerformComputation(addition, 10, 5);  // result1 = 10 + 5 = 15
        int result2 = PerformComputation(multiplication, 7, 3);  // result2 = 7 * 3 = 21

        Console.WriteLine("Result of addition: " + result1);
        Console.WriteLine("Result of multiplication: " + result2);
    }

    // Method to perform a computation using the provided delegate
    static int PerformComputation(Computation computation, int a, int b)
    {
        return computation(a, b);
    }
}

In this example, we define a delegate `Computation` that represents a computation that takes two integers and returns an integer. We then define two computations using lambda expressions: addition and multiplication. We can pass these computations as data to the `PerformComputation` method and execute them dynamically based on the provided inputs.

No comments:

Post a Comment

Hot Topics