views:

109

answers:

4

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?

+9  A: 

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
You're saying assemblies so the original class's methods as a DLL file will work just fine, right?
Shaza
@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
A: 

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
A: 

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.

Keivan
A: 

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