Reputation: 1207
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.
Upvotes: 1
Views: 1113
Reputation: 292555
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);
Upvotes: 3