Tomtom
Tomtom

Reputation: 9394

Make class serializable while runtime

I have a small Library where the user can set and get properties by using an generic interface. So the user can set every object he or she wants.

Than I have a method to save the properties to the file-system using the BinaryFormatter. With native types like string or DateTime or ... everything works fine. But if the user has a custom class like

class User
{
    public string Name { get; set; }
}

than I get an Exception, that the class Person is not market as Serializable. If I write the [Serializable] attribute about my class it just works fine.

My question is now: Is there a way that I can declare a class as Serializable in runtime? So if the user forgot to do so, I can try it?

The code for the Serialization looks like:

public void Save(string saveFilePath)
{
    byte[] binaryData;
    using (var memoryStream = new MemoryStream())
    {
        var binaryFormatter = new BinaryFormatter();
        binaryFormatter.Serialize(memoryStream, AllProperties);
        binaryData = memoryStream.ToArray();
    }
    File.WriteAllBytes(saveFilePath, binaryData);
}

Upvotes: 3

Views: 389

Answers (1)

Yuval Itzchakov
Yuval Itzchakov

Reputation: 149618

Attributes in C# are static metadata. They can't be injected at runtime. What you can do is use reflection on a System.Type to search that metadata at runtime.

The user declaring the class will have to do so at compile-time.

Upvotes: 2

Related Questions