0

I converted my project to .net core 3.1 (c#), now when I'm trying to binary serialize a Lazy<T> object I get a System.Runtime.Serialization.SerializationException.

Is there a way to do that?

this example code works in .net framework and throws exception in .net core:

class Program
{
    static void Main(string[] args)
    {
        var lazyS = new Lazy<LazyObject>(() => { return new LazyObject(); });
        UtilityLibrary.TestSerializable(lazyS);
        Console.ReadLine();
    }
}

public static class UtilityLibrary
{
    public static void TestSerializable(object obj)
    {
        if (obj == null)
            return;

        Type t = obj.GetType();
        Console.WriteLine($"isSerializable - {t.IsSerializable}");

        var formatter = new BinaryFormatter();
        using (var stream = new FileStream("data.bin", FileMode.Create,
                                    FileAccess.Write, FileShare.None))
        {
            formatter.Serialize(stream, obj);
        }
        // Deserialize the value tuple.
        using (var readStream = new FileStream("data.bin", FileMode.Open))
        {
            object restoredValue = formatter.Deserialize(readStream);
            Console.WriteLine($"{restoredValue.GetType().Name}: {restoredValue}");
        }
    }
}
Amir M
  • 508
  • 1
  • 8
  • 28
  • 4
    What would you expect to happen? How does one serialize a `Func`? – nvoigt Jul 14 '20 at 14:14
  • @nvoigt how does it work in .net farmework? – Amir M Jul 14 '20 at 14:22
  • 1
    I have a hard time believing that it *did* work. If you have a `Lazy` and the `Func` to create it is a lambda expression like `() => context.Xs.First(x => x.y == 5)` then what could be possibly serialized about that? What happend when you did? – nvoigt Jul 14 '20 at 14:45
  • @nvoigt I understand what you are saying but how come the sample code I added works on ,net framwork? – Amir M Jul 14 '20 at 15:11
  • 1
    `BinaryFormatter` is considered obsolete and dangerous, and the core framework folks are trying very hard to kill it completely; I strongly advise *not* going this direction – Marc Gravell Jul 14 '20 at 15:13
  • 1
    @nvoigt: on desktop, serialization of a `Lazy` object triggers evaluation of the factory delegate, and the value itself is serialized, rather than the delegate. See e.g. https://stackoverflow.com/questions/17921035/why-lazyt-forces-initialization-during-serialization – Peter Duniho Jul 14 '20 at 16:22
  • While `BinaryFormatter` can in theory serialize some (but not all) delegates, doing so is a **bad idea**. For why see [how come BinaryFormatter can serialize an Action<> but Json.net cannot](https://stackoverflow.com/a/49139733). – dbc Jul 14 '20 at 22:24

0 Answers0