Func<T> as class member, access other members of instance
c#, func, lambda
Solution
You can use closures. A closure will be an anonymous delegate or lambda expression which may reference variables, methods, properties, events or anything from an outer scope (oops, it's your case!).
leonardo.DoNinjaMove = (move) => {
// THIS IS VALID! IT'S A CLOSURE! You can access leonardo reference within
// the closure!!
if(move == "katana slash") return leonardo.Sound;
return "zirp zirp zirp";
}
Anyway, `DoNinjaMove` is `Func<string, bool>`. If you want to return `Sound` value, it should be refactored to `Func<string, string>`.
Further details about how closures work and why you can safely use outer scope's references within them can be found on this other Q&A here in StackOverflow:
- How do closures work behind the scenes? (C#)
About if using closures would work when working with satellite assemblies and so...
Yes, there's no problem with that. Closures are a very interesting feature that most modern languages own and it's a must-have feature for languages that have incorporated functional programming. Anyway, it's a must-have feature! :)
Problem
I have a question wheater or not it is possible (and if it is, how) to access `class` members from inside a `Func<T, TResult>` delegate. For example, I have the following `class`: ``` class NinjaTurtle { public string Sound { get; set; } public Func<string, string> DoNinjaMove { get; set; } } ``` Now I'd like to do this ``` NinjaTurtle leonardo = new NinjaTurtle(); leonardo.Sound = "swiishhh!"; leonardo.DoNinjaMove = (move) => { if(move == "katana slash") return leonardo.Sound; return "zirp zirp zirp"; } ``` The problem is, how do I correctly access the property `Sound`, when I define the callback function? Is it OK to just use the reference to the instance from outside the function? Would this still work when I pass the object to another method, or even when this would be part of a dll, and I would return the object leonardo from a function in the dll? Would it "survive" serialization / deserialization? (Thanks Vladimir and Lee, the question is now more specific to what I would like to know).