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}");
}
}
}