Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

C# Querying With LINQ Functional Programming in C# Lambda Expressions

I am trying to write lambda expression for Action, but it is not compiling.

The program states that I am not using the same variables as used in definition.

Program.cs
using System;

namespace Treehouse.CodeChallenges
{
    public class Program
    {     
        public Func<int, int> Square = (int number) => (number * number);

        public Action<int, Func<int, int>> DisplayResult = (int result, Func<int, int> function) => Console.WriteLine(function(result));

        static void Main(string[] args)
        {

        }
    }
}

2 Answers

Steven Parker
Steven Parker
231,248 Points

:point_right: You don't need the argument types in the lambda expression, they are inferred by the compiler:

        public Action<int, Func<int, int>> DisplayResult = (result, function) => Console.WriteLine(function(result));
Ryan Sheppard
Ryan Sheppard
2,866 Points

The code you posted compiles fine for me -- double check you saved Program.cs before you compile it...

But FYI you won't be able to use the Square Func or the DisplayResult Action in the Main method because Square and DisplayResult are instance members while Main is a static method -- static methods can't access instance members.

You would need to make Square and DisplayResult static if you want to access them inside Main.