Click here to Skip to main content
6,629,377 members and growing! (20,494 online)
Email Password   helpLost your password?
Languages » C# » General     Intermediate License: The Code Project Open License (CPOL)

Anonymous Method Serialization

By chot

Anonymous method serialization
C#, Windows, Dev
Version:3 (See All)
Posted:12 Feb 2009
Views:5,246
Bookmarked:14 times
Announcements
Loading...
 
Search    
Advanced Search
Add to IE Search
printPrint   add Share
      Discuss Discuss   Broken Article?Report  
4 votes for this article.
Popularity: 2.33 Rating: 3.88 out of 5

1

2
1 vote, 25.0%
3
1 vote, 25.0%
4
2 votes, 50.0%
5

Introduction

Anonymous methods cannot be serialized in C# (unless they do not reference any stack variables). The most simple solution would be to add the [Serializable] attribute to the anonymous class generated for the method, but since this is (as far as I know) not possible yet, we have to use this "hack".

This is an updated version of Jeremy Thomas' version that can be found here, with the improvement that this also supports nested delegates, and any delegate.

Please note that this code is not very well tested.  Also note that anything you reference inside the anonymous method also gets serialized, including this. This means that, if you serialize a delegate referencing this and then deserialize it again and run it, then this will refer to a new copy of the object.

Using the Code 

formater.Serialize(stream, new SerializeDelegate(myDelegate));

Code

[Serializable]
public class SerializeDelegate : ISerializable
{
    internal SerializeDelegate(Delegate delegate_)
    {
        this.delegate_ = delegate_;
    }

    internal SerializeDelegate(SerializationInfo info, StreamingContext context)
    {
        Type delType = (Type)info.GetValue("delegateType", typeof(Type));

        //If it's a "simple" delegate we just read it straight off
        if (info.GetBoolean("isSerializable"))
            this.delegate_ = (Delegate)info.GetValue("delegate", delType);

        //otherwise, we need to read its anonymous class
        else
        {
            MethodInfo method = (MethodInfo)info.GetValue("method", typeof(MethodInfo));

            AnonymousClassWrapper w = 
                (AnonymousClassWrapper)info.GetValue
			("class", typeof(AnonymousClassWrapper));

            delegate_ = Delegate.CreateDelegate(delType, w.obj, method);
        }
    }

    void ISerializable.GetObjectData(SerializationInfo info, StreamingContext context)
    {
        info.AddValue("delegateType", delegate_.GetType());

        //If it's an "simple" delegate we can serialize it directly
        if ((delegate_.Target == null ||
            delegate_.Method.DeclaringType
                .GetCustomAttributes(typeof(SerializableAttribute), false).Length > 0) &&
            delegate_ != null)
        {
            info.AddValue("isSerializable", true);
            info.AddValue("delegate", delegate_);
        }

        //otherwise, serialize anonymous class
        else
        {
            info.AddValue("isSerializable", false);
            info.AddValue("method", delegate_.Method);
            info.AddValue("class", 
                new AnonymousClassWrapper
		(delegate_.Method.DeclaringType, delegate_.Target));
        }
    }

    public Delegate Delegate { get { return delegate_; } }

    Delegate delegate_;

    [Serializable]
    class AnonymousClassWrapper : ISerializable
    {
        internal AnonymousClassWrapper(Type bclass, object bobject)
        {
            this.type = bclass;
            this.obj = bobject;
        }

        internal AnonymousClassWrapper(SerializationInfo info, StreamingContext context)
        {
            Type classType = (Type)info.GetValue("classType", typeof(Type));
            obj = Activator.CreateInstance(classType);

            foreach (FieldInfo field in classType.GetFields())
            {
                //If the field is a delegate
                if (typeof(Delegate).IsAssignableFrom(field.FieldType))
                    field.SetValue(obj,
                        ((SerializeDelegate)info.GetValue
				(field.Name, typeof(SerializeDelegate)))
                            .Delegate);
                //If the field is an anonymous class
                else if(!field.FieldType.IsSerializable)
                    field.SetValue(obj,
                        ((AnonymousClassWrapper)info.GetValue
				(field.Name, typeof(AnonymousClassWrapper)))
                            .obj);
                //otherwise
                else
                    field.SetValue(obj, info.GetValue(field.Name, field.FieldType));
            }
        }

        void ISerializable.GetObjectData
		(SerializationInfo info, StreamingContext context)
        {
            info.AddValue("classType", type);

            foreach (FieldInfo field in type.GetFields())
            {
                //See corresponding comments above
                if (typeof(Delegate).IsAssignableFrom(field.FieldType))
                    info.AddValue(field.Name, new SerializeDelegate
					((Delegate)field.GetValue(obj)));
                else if (!field.FieldType.IsSerializable)
                    info.AddValue(field.Name, new AnonymousClassWrapper
				(field.FieldType, field.GetValue(obj)));
                else
                    info.AddValue(field.Name, field.GetValue(obj));
            }
        }

        public Type type; 
        public object obj;
    }
}

History

  • 12th February, 2009: Initial post

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

About the Author

chot


Member

Occupation: Web Developer
Location: Sweden Sweden

Other popular C# articles:

Article Top
You must Sign In to use this message board.
FAQ FAQ 
 
Noise Tolerance  Layout  Per page   
 Msgs 1 to 7 of 7 (Total in Forum: 7) (Refresh)FirstPrevNext
GeneralUnable to deserialize Pinmemberpadanfain7:21 16 Jun '09  
GeneralRe: Unable to deserialize Pinmemberchot12:40 19 Aug '09  
GeneralA question... PinsupporterMarc Clifton2:37 23 Feb '09  
GeneralSerializing/reconstituting delegates Pinmembersupercat917:11 12 Feb '09  
GeneralRe: Serializing/reconstituting delegates Pinmemberchot1:27 13 Feb '09  
GeneralRe: Serializing/reconstituting delegates Pinmembersupercat913:21 13 Feb '09  
GeneralRe: Serializing/reconstituting delegates Pinmemberchot15:34 13 Feb '09  

General General    News News    Question Question    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

PermaLink | Privacy | Terms of Use
Last Updated: 12 Feb 2009
Editor: Deeksha Shenoy
Copyright 2009 by chot
Everything else Copyright © CodeProject, 1999-2009
Web19 | Advertise on the Code Project