3

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);
}
WeSt
  • 2,628
  • 5
  • 22
  • 37
Tomtom
  • 9,087
  • 7
  • 52
  • 95
  • I am pretty sure you can't, see http://stackoverflow.com/questions/129285/can-attributes-be-added-dynamically-in-c It would be a bad practice as well I would say – DerApe Sep 11 '14 at 08:57
  • you can make use libraries like http://www.sharpserializer.com/en/index.html or xmlserialisation would work too. but as derape said, it's bad practice to do that – user1519979 Sep 11 '14 at 09:02
  • Ok. Thank you. Than the user will have to take responsibility for that. – Tomtom Sep 11 '14 at 09:10

1 Answers1

2

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.

Yuval Itzchakov
  • 146,575
  • 32
  • 257
  • 321