4

Is there a way to make serializable an object at runtime? Should I use Reflection?

Note: the object is part of an external library, so I do not have the source code for it.

Stephen Kennedy
  • 20,585
  • 22
  • 95
  • 108
Rick
  • 1,042
  • 2
  • 14
  • 34
  • Please explain what you mean by "making serializable". What _exactly_ are you trying to do? – CodeCaster Nov 16 '14 at 12:52
  • add the [Serializable] attribute to the class – Rick Nov 16 '14 at 12:55
  • 1
    Now that is a specific question you can search for. See [Can attributes be added dynamically in C#?](http://stackoverflow.com/questions/129285/can-attributes-be-added-dynamically-in-c). – CodeCaster Nov 16 '14 at 12:58

2 Answers2

4

tl;dr - No.

While you can use TypeDescriptor to add attributes to anything at runtime, in the context of the Serializable attribute it won't help since BinaryFormatter uses classic reflection and not TypeDesciptor reflection.

The idea behind that attribute is for the serializable class to opt-in to being serializable. More details about this here.

Community
  • 1
  • 1
Moti Azu
  • 5,392
  • 1
  • 23
  • 32
0

Depending on the structure you could possibly use a serializer which is not opt-in i.e. it does not require any attribute on the target class, for example the XmlSerializer or Json.NET.

Stephen Kennedy
  • 20,585
  • 22
  • 95
  • 108