10

The title is obvious, I need to know if methods are serialized along with object instances in C#, I know that they don't in Java but I'm a little new to C#. If they don't, do I have to put the original class with the byte stream(serialized object) in one package when sending it to another PC? Can the original class be like a DLL file?

John Saunders
  • 160,644
  • 26
  • 247
  • 397
Lisa
  • 3,121
  • 15
  • 53
  • 85

4 Answers4

16

No. The type information is serialized, along with state. In order to deserialize the data, your program will need to have access to the assemblies containing the types (including methods).

Reed Copsey
  • 554,122
  • 78
  • 1,158
  • 1,373
  • You're saying assemblies so the original class's methods as a DLL file will work just fine, right? – Lisa May 04 '10 at 18:25
  • 1
    @Shaza: Yes. Both sides (serialization and deserialization) need to have the assembly (typically DLL) containing the type being serialized. This needs to be discoverable in order for the type to be instanced correctly by the serialization classes. – Reed Copsey May 04 '10 at 18:35
12

It may be easier to understand if you've learned C. A class like

class C
{
    private int _m;
    private int _n;

    int Meth(int p)
    {
       return _m + _n + p;
    }
}

is essentially syntactic sugar for

typedef struct
{
   int _m;
   int _n;
   // NO function pointers necessary
} C;

void C_Meth(C* obj, int p)
{
   return obj->_m + obj->_n + p;
}

This is essentially how non-virtual methods are implemented in object-oriented languages. The important thing here is that methods are not part of the instance data.

dan04
  • 87,747
  • 23
  • 163
  • 198
  • but what happens when the class C in above example has virtual methods? Will the vtable get serialized as well? If that is the case then when you restore (deserialize) the object from a file to a new instance of the application, the address in vtable is not guaranteed to point to the function right? Do you know how .Net handles this? – Social Developer Jan 15 '20 at 12:29
2

Methods aren't serialized.

I don't know about your scenario, but putting in a library (assembly / dll) and using that in the other end to deserialize gets you all.

Ps. you probably should create some ask some more questions with the factors involved in your scenario. If you are intending to dynamically send & run the code, you can create awful security consequences.

eglasius
  • 35,831
  • 5
  • 65
  • 110
1

I was confused when .NET first came up with serialization. I think it came from the fact that most books and guides mention that it allows you to serialize your 'objects' as XML and move them around, the fact is that you are actually hydrating the values of your object so you can dehydrate them latter. at no point your are saving your whole object to disk since that would require the dll and is not contained in the XML file.

kay.one
  • 7,622
  • 6
  • 55
  • 74