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 trialAaron Selonke
10,323 PointsAction and Func Challange
Trying to pass the challenge, and just as I'm getting my head around the syntax and reasons of delegates, The challenge asks my to use the Func<> as a parameter for the Action<>
This code won't compile, I'm not sure why or where to begin even...
Thanks in Advance
using System;
namespace Treehouse.CodeChallenges
{
public class Program
{
public Func<int, int> Square = delegate(int number)
{
return number * number;
};
public Action<int, Func<int,int>> DisplayResult;
DisplayResult = delegate (int result, Func<int,int> operation)
{
};
}
}
Aaron Selonke
10,323 PointsThis won't compile either, It will only work when the DisplayResult Delegate is called on the same statement as the Action<> ???
Still figuring out the Actions and Funcs, but in the video she is able to call the delegate's and the Action/Func separately in separate statements......
Find any good resources for Actions/Funcs outside of the MSDN or Treehouse?
public Func<int, int> Square = delegate (int number)
{
return number * number;
};
public Action<int, Func<int, int>> DisplayResult;
DisplayResult = delegate (int result, Func<int, int> operation)
{
Console.WriteLine(operation(result));
};
1 Answer
David Valentin
7,058 PointsYeah, I saw that she declared it too, and that threw me off as well. Apparently you have to do it all in one line. :/
I dropped your code in Visual Studio, a C# Editor, and basically your issue is your declaring DisplayResult as an Action without any delegate, than assigning a delegate to it, so the compiler will whine to you saying, "There already exists a definition of DisplayResults. "
During compile time you have these two declarations of DisplayResults.
I'm pretty sure its because C# is (partially) strongly typed. The way you have it declared DisplayResults is that its an action delegate type, and than later its given more detail, when you should immediately declare all the details of your variable like its input params during its declaration.
C# Strongly Typed/Weakly Typed: https://ericlippert.com/2012/10/15/is-c-a-strongly-typed-or-a-weakly-typed-language/
Hope that helps!
David Valentin
7,058 PointsDavid Valentin
7,058 PointsFirst the reason why your solution is incorrect is because your not assigning your Action to a delegate which takes an (int, Func<int,int>) as its parameters.
Solution: