I wrote a program that serializes/deserializes some data based on the code you provided, and it works fine.
You said:
But I get a null value. Debugging the code shows that the function works. The result object is a list.
There is a subtle difference between 2 casting operations in C#
string text = (string)GetString(); // throws exception if cannot be cast
string text = GetString() as string; // returns null if source cannot be cast
Other than that, based on the limited amount of info that you provided, we won't be able to help you further troubleshoot.
Can you narrow it down to the line of code that isn't working? Are you sure that the serialization is working properly?
using System;
using System.Collections.Generic;
using System.IO;
using System.Runtime.Serialization.Formatters.Binary;
namespace Cereal
{
class Program
{
static void Main(string[] args)
{
string file = Path.Combine(Environment.CurrentDirectory, "cereal.bin");
List<string> namesToWrite = new List<string>();
namesToWrite.Add("Frosted Flakes");
namesToWrite.Add("Fruit Loops");
namesToWrite.Add("Lucky Charms");
namesToWrite.Add("Apple Jacks");
Serialize(file, namesToWrite);
List<string> namesToRead = Deserialize(file) as List<string>;;
foreach (string name in namesToRead)
{
Console.WriteLine(name);
}
Console.ReadLine();
}
static void Serialize(string file, object stuff)
{
var fmt = new BinaryFormatter();
using (FileStream fs = File.Open(file, FileMode.Create))
{
fmt.Serialize(fs, stuff);
}
}
static object Deserialize(string file)
{
var ret = new object();
var fmt = new BinaryFormatter();
using (FileStream fs = File.Open(file, FileMode.Open))
{
ret = fmt.Deserialize(fs);
}
return ret;
}
}
}