In a WebControl
, i have a property Filters
defined like this :
public Dictionary<string, Func<T, bool>> Filters
{
get
{
Dictionary<string, Func<T, bool>> filters =
(Dictionary<string, Func<T, bool>>)ViewState["filters"];
if (filters == null)
{
filters = new Dictionary<string, Func<T, bool>>();
ViewState["filters"] = filters;
}
return filters;
}
}
This webcontrol is a DataSource
, i created this property because i want to have the possiblity to filter data easily, eg:
//in page load
DataSource.Filters.Add("userid", u => u.UserID == 8);
It works great, however, if I change code to this :
//in page load
int userId = int.Parse(DdlUsers.SelectedValue);
DataSource.Filters.Add("userid", u => u.UserID == userId);
It doesn't works anymore, I get this error :
Type System.Web.UI.Page in Assembly '...' is not marked as serializable.
What happened :
- The serializer inspect the dictionary. It sees it contains a anonymous delegate (lambda here)
- Since the delegate is defined in a class, it tries to serialize the whole class, in this case System.Web.UI.Page
- This class is not marked as Serializable
- It throws an exception because of 3.
Is there any convenient solution to solve this ? I cannot mark all web pages where i use the datasource as [serializable] for obvious reasons.
EDIT 1 : something I don't understand. If I store the Dictionary
in the Session
object (which use a BinaryFormatter
vs LosFormatter
for ViewState
), it works ! I have no idea how it is possible. Maybe BinaryFormatter
can serialize any class, even these who are not [serializable]
?
EDIT 2 : smallest code to reproduce the problem :
void test()
{
Test test = new Test();
string param1 = "parametertopass";
test.MyEvent += () => Console.WriteLine(param1);
using (MemoryStream ms = new MemoryStream())
{
BinaryFormatter bf = new BinaryFormatter();
bf.Serialize(ms, test); //bang
}
}
[Serializable]
public class Test
{
public event Action MyEvent;
}