0
0
C Sharp (C#)programming~15 mins

Lambda with captures (closures) in C Sharp (C#) - Mini Project: Build & Apply

Choose your learning style9 modes available
Lambda with captures (closures) in C#
📖 Scenario: Imagine you are creating a simple calculator that can remember a number and add it to other numbers later.
🎯 Goal: You will build a small program that uses a lambda function to remember a number (capture it) and add it to new numbers when called.
📋 What You'll Learn
Create an integer variable called baseNumber with the value 10
Create a lambda function called addBase that takes an integer parameter x and returns the sum of baseNumber and x
Call the lambda function addBase with the value 5 and store the result in a variable called result
Print the value of result
💡 Why This Matters
🌍 Real World
Closures like this are useful when you want to create small functions that remember some data without needing to pass it every time.
💼 Career
Understanding closures helps in writing clean, reusable code in many programming jobs, especially when working with events, callbacks, or functional programming styles.
Progress0 / 4 steps
1
Create the base number
Create an integer variable called baseNumber and set it to 10.
C Sharp (C#)
Need a hint?

Use int baseNumber = 10; to create the variable.

2
Create the lambda function with capture
Create a lambda function called addBase that takes an integer parameter x and returns the sum of baseNumber and x.
C Sharp (C#)
Need a hint?

Use Func<int, int> and a lambda expression like x => baseNumber + x.

3
Call the lambda function
Call the lambda function addBase with the value 5 and store the result in a variable called result.
C Sharp (C#)
Need a hint?

Call addBase(5) and assign it to result.

4
Print the result
Print the value of the variable result using Console.WriteLine.
C Sharp (C#)
Need a hint?

Use Console.WriteLine(result); to show the output.