In my code I have a new item property setter in the form of lambda expression. It's as simple as
( x ) => x.Property = y
I wrote it to an Action<T>
variable and I've been using it when needed.
The problem is, when I was "printing" object that was sent to that lambda as an input to gui, I found out that the property remains as null.
I've tried debugging it and while in that lambda expression, I can see that the object's property is being set to desired value, but the moment I step out of lambda, Property is back to null. For some reason, it's as if lambda operates on a copy of this object instead of it's reference?? I've tried rewriting it to delegate void ActionRef<T>( ref T item )
(which I came up with after some reading of SO questions) but this worked exactly the same way.
Finally, I've tried with Func<T,T>
and somehow again, it returns an object with property still set to null. I've even tried setting some default type properties (string, int, DateTime) just to test if there is something wrong with objects of my custom classes, but no, those also weren't properly set after leaving the lambda.
I seriously have no clue what can be the reason for that. I even wrote a simple test app that does similar stuff and it works just fine. It is first time I have problems with lambdas.
I doubt that code samples are really needed here, but in case someone needs that:
class A {
A ( Action<T> setter ) {
newItemPropertySetter = setter;
}
void InsertNewItem() {
…
T item = new T();
if ( newItemPropertySetter != null )
newItemPropertySetter( item );
…
}
}
class B {
…
… = new A( ( x ) => x.Property = y );
…
}
Finally, one last thing that just came to me is something that might be somehow related to this strange issue - T classes are my ORM classes used with nHibernate. This still does not help me understand why property I've set to some value suddenly is unset back to null / default.
Edit: After quite a bit of debugging, I've found out that in the end some other piece of code was immediately overwriting that property with default value. Sorry for the trouble.