Question

I need to serialize static class with BinaryFormatter, here is the code:

    void Serialize()
    {
        IFormatter formatter = new BinaryFormatter();

        using (FileStream s = File.Create("ServerInfo.bin"))
            formatter.Serialize(s, Server); // ERROR: Error 44 'Server' is a 'type' but is used like a 'variable'

    }

How can i fix this?

Was it helpful?

Solution

You normally serialize instances. You can't have an instance of a static class, so it makes no sense to serialize it.

If you need to serialize the static state of a static class, then you should probably make it non-static to start with. If you really need to keep the static class static but serialize the static state, you could create a normal class with the same variables (but instance variables instead of static ones), and make methods in your static class to create an instance from the current static state, or replace the current static state based on an instance passed in. But fundamentally it's not terribly pleasant to do so...

OTHER TIPS

You can only serialize objects. Let's assume the Server class looks like this.

class Server
{
    public static string Name { get; set; }
    public static string IpAddresss { get; set; }
}

You cannot serialize this as there is no object to serialize. You could serialize the strings, but that's not what you want to do.

You can use the Singleton pattern to do this.

class Server
{
    private static Server _instance;
    public string Name { get; set; }
    public string IpAddress { get; set; }

    public static Server Instance 
    { 
        get { return _instance ?? ( _instance = new Server(); }
    }
}

There might be some issues with this, as I coded it in the browser.

The point of serialization is to serialize the state of an object and given static classes cannot be instantiated this suggests they aren't fit for serialization.

How can I fix this?

Consider creating a temporary class for serialization e.g. ServerState, transfer any state you want to store and use that instead

public static class Server
{
    public static ServerState CurrentState
    {
        return new ServerState
        {
            ...
        };
    }

    public static void LoadState(ServerState state)
    {
        ...
    }
}

...
IFormatter formatter = new BinaryFormatter();

using (FileStream s = File.Create("ServerInfo.bin"))
    formatter.Serialize(s, Server.CurrentState);

Most likely, what you want is to save the values of the variables. Just write a method in the class to do so. You can use any of the writer classes provided for streams and you can read them back using one of the reader classes.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top