I'm learning/experimenting with some functional patterns within C# and I've hit a bump I can't quite explain. I'm sure it's a simple answer (I hope) but I'm struggling to see it. Likely has to do with closures, etc and my inability to get out-of-box is hiding the answer from me!
Here's my experiment: I'm trying to return a brand new instance of a particular class from within a function delegate..
public class Foo{
string A { get; set ; }
}
static void Main( string[] args ){
// the delegate...
Func<Foo,bool> someFunc = o => {
o = new Foo { A = "A new instance of o?" };
return true;
};
Foo foo = null; // was hoping to replace this via delegate
var myFunc = someFunc;
var result = myFunc( foo );
if ( foo == null )
Console.WriteLine( "foo unchanged :-(" );
else
Console.WriteLine( foo.A ); // hoping for 'A new instance of o?'
Of course, I just get "foo unchanged :-(" in my output. I made a slight variation on the test where I passed in a non-null Foo instance and modified the property "A" (vs returning a new instance) and that worked okay (that is, I can mutate an existing object just like I would expect when passing object references to functions) I just can't seem to get a new instance out of my delegate.
So? Am I just doing something wrong in the code? Can this be done at all? Would love to understand why this doesn't work.
You can return the
Fooas the return value of the lambda expression:Or you can return a
Tuple<bool, Foo>if you really need to return abool:Or, if you're really really sure you want that, you can declare your own custom
Func-like delegate with anoutparameter:But I wouldn't recommend that.