@ozair said in CS508 GDB 1 Solution and Discussion:
Re: CS508 GDB.1 Solution and Discussion
Total Marks 5
Starting Date Monday, February 15, 2021
Closing Date Tuesday, February 16, 2021
Status Open
Question Title GDB
Question Description
In a programming world, Lambda Expression (i.e. lambda function) is essentially a block of code that can be assigned to a variable, passed as an argument, or returned from a function call. It has been part of several programming languages like Smalltalk, Lisp, Ruby, Scala, Python, Java and C# etc. for quite some time.
In context of C# programming, a lambda can be used instead of an anonymous method/function where we do not need to provide access modifier, return type and even name of the method. For example, the following anonymous method checks if a student is teenager or not:
Listing 1: (anonymous method in C# to check if a student is teenager or not)
delegate(Student std) {
return std.Age > 12 && std.Age < 20;
}
While the same functionality can be achieved by using lambda as;
Listing 2: (checking if a student is teenager or not using lambda in C#)
std => std.Age > 12 && std.Age < 20;
Here, we can see that the code has been shortened (i.e. writability increased). However, it makes the code relatively difficult to understand as “std” in listing 2 is ambiguous (i.e. readability decreased). But what about Reliability?
Being a programming language expert, you are required to compare both approaches (i.e. code written with/without lambda) and state which one is better in terms of Reliability in C# programming language.
Anonymous methods can also be passed to a method that accepts the delegate as a parameter.
In the following example, PrintHelperMethod() takes the first parameters of the Print delegate:
Example: Anonymous Method as Parameter
public delegate void Print(int value);
class Program
{
public static void PrintHelperMethod(Print printDel,int val)
{
val += 10;
printDel(val);
}
static void Main(string[] args)
{
PrintHelperMethod(delegate(int val) { Console.WriteLine("Anonymous method: {0}", val); }, 100);
}
}