Consider this lambda expression: (a, b, c) => a + b + c Would this work as an ar
ID: 3879887 • Letter: C
Question
Consider this lambda expression:
(a, b, c) => a + b + c
Would this work as an argument to genMath.DoMathProblem? Why or why not. (see code below).
------------------------------------------------------------------------------------------------------------------------------------------------------
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Assignment1c
{
class Program
{
static void Main(string[] args)
{
Console.Write("Enter first operand: ");
double num1 = double.Parse(Console.ReadLine());
Console.Write("Enter second operand: ");
double num2 = double.Parse(Console.ReadLine());
GenericMath genMath = new GenericMath() { Operand1 = num1, Operand2 = num2 };
double sum = genMath.DoMathProblem((o1, o2) => o1 + o2);
Console.WriteLine($"The sum is {sum}");
double diff = genMath.DoMathProblem((o1, o2) => o1 - o2);
Console.WriteLine($"The difference is {diff}");
double mult = genMath.DoMathProblem((o1, o2) => o1 * o2);
Console.WriteLine($"The product is {mult}");
double div = genMath.DoMathProblem((o1, o2) =>
{
if (o2 != 0)
return o1 / o2;
else
{
throw new DivideByZeroException();
}
});
Console.WriteLine($"The quotient is {div}");
#if DEBUG
Console.WriteLine("Press enter to close...");
Console.ReadLine();
#endif
}
/*static double Add(double operand1, double operand2)
{
return operand1 + operand2;
}*/
/*static double Subtract(double operand1, double operand2)
{
return operand1 - operand2;
}*/
}
}
Explanation / Answer
Hi,
No, the argument "(a, b, c) => a + b + c" will not work as a parameter for genMath.DoMathProblem method. This is because we have defined only two operand namely operand 1 and operand 2 while creating the object for GenericMath class. And we have defined 4 operations on these two operands namely addition, multiplication, subtraction and division.
All of these operations can be applied to two operands as per current code. But, the given scenario, we are trying to perform addition operation on 3 operands a,b and c which is invalid and will result and error