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!

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#

Aaron Selonke
Aaron Selonke
10,323 Points

Funcs and Delegate Questions

1)Are Funcs derived from Delegates? 2) I know how they work, but what does it mean that Funcs 'encapsulate' a method? Why is that valuable? 3) It looks like Linq extension methods make a lot of use of Funcs, But do Do C# programmers usually use written out Delegates (method signatures) in modern programming practice? I only see people make examples of using them for events and event handlers..

Thanks

1 Answer

Lewis Cowles
Lewis Cowles
74,902 Points

1) No clue how it works under the hood, but I feel it's irrelevant as programming languages have to change implementation details all the time; it's the public API (how we use the language) that often remains familiar unless it has to change between major versions of a program. C# has two runtimes as I understand it, Mono and the official .NET runtimes.

2) Encapsulation means that it exists within it's own context (similar to it's own sheet of paper, or own book); rather than the global namespace and does not need to worry about external effects. If an objects instance has a variable or property named name, and another instance has the same name, and has not been marked to share a context; then changes to one won't affect the other (it's likely an object or struct, but the idea is it's contained or confined to it's own area and should only operate upon it's own state). The same would be true of two event handlers without the context persisting you could not easily store an incremented value for example. Of course if you used an object or the Func or Delegate existed outside of it's use you could provide mechanisms to overcome this.

3) Subjective at best it will depend upon team preference. I prefer fully qualified objects and am against using Funcs and Delegates if I can avoid without using too much mind-share; some may prefer them where they are an option, so it really does depend. Pick what works for you and know the benefits and drawbacks