Event handlers and memory usage

6

6tc1

Hi all, I'm inquiring about the mechanism that is used to implement
event handlers in .NET (not really relevant, but I'm using C#).
Anyway, I've noticed that I can pass an object in an event argument and
if the receiver (event handler) of that event changes any of the
properties in that object, then the original object I passed is
changed. I.E. it seems as if events are passed by reference and not by
value. This certainly frees me up from trying to optimize memory usage
when I'm passing objects (or actually their references) through event
arguments.

I was thinking that events were serialized - but it seems that isn't
the case. Since if they were being serialized then any changes made to
the object by the event handler shouldn't affect the original that was
passed as an argument.

Hope this is clear - the reason I'm asking this is because I have a
rather large object that I'm passing as an event argument and I was
going through the code in an attempt to optimize only to realize that
there doesn't appear to be any performance benefit to passing a unique
identifier string for that object and then find that object in my
database or whether I just pass this entire massive object.

Thanks,
Novice
 
K

Kevin Spencer

All reference types are passed by reference. What this means is that a
managed pointer to the object is passed. Passing by value passes a copy of
an object. Primitives and value types are passed by value.

Think of it this way: If I mail you a copy of my house, I mail an entire
house to you. But if I mail you the address of my house, I can fit it on a
single sheet of paper. And if you enter the copy of my house I won't see
you. But if you come to the address of my house and enter it, I can see you.

--
HTH,

Kevin Spencer
Microsoft MVP
..Net Developer
A brute awe as you,
a Metallic hag entity, eat us.
 
6

6tc1

heh heh... I understand the difference between passing by copy and
value... but good analogy none the less...

I just thought events were being serialized... and that any argument
handed to them (be they primitive data type or not) were copied/cloned.

I guess I'll have to look elsewhere for optimizations - i.e. no sense
in reconstructing the object from the database, if I'm just passing a
reference to it.

Thanks,
Novice
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top