Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Do C# reference types allocates new memory when passed to methods?

everyone... I'm new to C# and such languages...

I've read two articles by Skeet, one about heap/stack, and other about reference types and value types. And I assume my question is simple, but it's not clarified to me after reading those articles.

Do reference types allocate new memory when passed to methods?

For example, if I pass a Form to a method, like

void myMethod(System.Windows.Forms.Form myForm)
{
...
}

Will there be more memory allocated to store all myForm data or will it hold just a reference to where myForm data is already allocated?

My worry is that if there's more memory allocated to store everything "appended" to myForm, soon the memory could become full, if myForm were a big form...

like image 252
Girardi Avatar asked Dec 01 '22 09:12

Girardi


1 Answers

When you instantiate your original form, the form object will allocated on the heap. When you call myMethod, you're passing a reference type (essentially a pointer to that object) by value. That means that the reference you're passing in will be copied in the context of myMethod - this involves a 32/64 bit stack allocation, depending on your architecture.

So, to answer your question, your form will not be copied but the reference to it will be.

Disclaimer: I haven't used C# in ages.

like image 113
asdfjklqwer Avatar answered Dec 10 '22 03:12

asdfjklqwer