using System.Collections.Generic;
using System.Runtime.Serialization.Formatters.Binary;
public struct SerializableDelegate<T> where T : class
private string methodName;
static SerializableDelegate() {
if (!typeof(T).IsSubclassOf(typeof(Delegate))) {
throw new InvalidOperationException(typeof(T).Name + " is not a delegate type.");
public SerializableDelegate(T action) {
var _delegate = action as Delegate;
throw new InvalidOperationException(typeof(T).Name + " is not a delegate type.");
target = _delegate.Target as Object;
methodName = _delegate.Method.Name;
methodName = _delegate.Method.Name;
if (cachedDelegate != null) {
if (methodName == null || methodName == "") {
return cachedDelegate = Delegate.CreateDelegate(typeof(T), target, methodName) as T;
public SerializableDelegate<Action> BarDelegate;
public SerializableDelegate<Func<int>> BarFunc;
BarDelegate = new SerializableDelegate<Action>(Bar);
Console.WriteLine($"{this.GetHashCode(),-10}{(x)}");
Console.WriteLine($"{this.GetHashCode(),-10}{(x * 2)}");
public static void Main()
foo2.BarDelegate = new SerializableDelegate<Action>(foo2.Bar2);
foo3.BarDelegate = new SerializableDelegate<Action>(foo2.Bar);
foo3.BarFunc = new SerializableDelegate<Func<int>>(foo1.Bar3);
var foos = new List<Foo>();
using (var stream = new MemoryStream())
var formatter = new BinaryFormatter();
formatter.Serialize(stream, foos);
using (var stream = new MemoryStream(data))
var formatter = new BinaryFormatter();
var deserializedFoos = formatter.Deserialize(stream) as List<Foo>;
foreach (var foo in deserializedFoos)
Console.Write($"BarDelegate: {foo.Equals(previous).ToString(),-10}");
foo.BarDelegate.GetDelegate().Invoke();
Console.WriteLine("BarFunc: " + foo.BarFunc.GetDelegate()?.Invoke());