views:

321

answers:

1

I currently have this:

instance = new Class1<Type1>(
                 "param1",
                 () =>
                 new ViewDataDictionary<Type2>(
                     new Class2
                    {
                        Prop1= CreateList(new List<long> { 234 }),
                         Prop2= CreateList(new long[] { 234 })
                     }) );

I want to pass a variable in the function CreateList instead. Something like this

long p1 = 123;
instance = new Class1<Type1>(
                     "param1",
                     () =>
                     new ViewDataDictionary<Type2>(
                         new Class2
                        {
                            Prop1= CreateList(new List<long> { p1}),
                             Prop2= CreateList(new long[] { p1})
                         }) );

But it gives me serialization error if I try to do the above. All the classes are marked serializable.

+2  A: 

When you reference a local variable in a lambda expression, it generates a closure (a compiler-generated class that "captures" your local variable as a field). This closure is not marked as serializable, so the serialization fails...

Instead, you could change the type of the lambda expression to accept a parameter, and pass the value as a separate parameter :

long p1 = 123;
instance = new Class1<Type1>(
                 "param1",
                 (prm) =>
                 new ViewDataDictionary<Type2>(
                     new Class2
                    {
                        Prop1= CreateList(new List<long> { prm }),
                         Prop2= CreateList(new long[] { prm })
                    }),
                 p1);
Thomas Levesque
I want to make this as a generic delegate. There could be a function that the delegate executes which could have no params or have more number of params. I was thinking of having an array of object. But is there a better way?
Well, in order to keep the class serializable, your lambda expression mustn't capture any local variable. So the only solution I see that would cover all cases is to use an array of objects (or maybe a dictionary) as a parameter to the delegate, even though it's not very convenient
Thomas Levesque