I'm working with the ref
and don't understand clearly "Is it like a pointer as in C/C++ or it's like a reference in C++?"
Why did I ask such a weak question as you thought for a moment? Because, when I'm reading C#/.NET books, msdn or talking to C# developers I'm becoming confused by the following reasons:
- C# developers suggest NOT to use
ref
in the arguments of a function,e.g. ...(ref Type someObject)
doesn't smell good for them and they suggest...(Type someObject)
, I really don't understand clearly this suggestion. The reasons I heard: better to work with the copy of object, then use it as a return value, not to corrupt memory by a reference etc... Often I hear such explanation about DB connection objects. As on my plain C/C++ experience, I really don't understand why to use a reference is a bad stuff in C#? I control the life of object and its memory allocations/re-allocations etc... I read in books and forums only advisesit's bad, because you can corrupt your connection and cause a memory leak by a reference lose
, so I control the life of object, I may control manually what I really want, so why is it bad? - Nowadays reading different books and talk to different people, I don't clearly understand is
ref
a pointer (*
) or a reference like in C++ by&
? As I remember pointers in C/C++ always do allocate a space with a size ofvoid*
type - 4 bytes (the valid size depends on architecture), where hosts an address to a structure or variable. In C++ by passing a reference&
there is no new allocations from the heap/stack and you work with already defined objects in memory space and there is no sub-allocating memory for a pointer externally like in plain C. So what's theref
in C#? Does .NET VM handle it like a pointer in plain C/C++ and itsGC
allocates temporary space for a pointer or it does a work like reference in C++? Doesref
work only with a managed types correctly or for value types likebool, int
it's better to switch anunsafe
code and pass through a pointer in unmanaged style?