Does declaration in c# allocate memory for the variable to be created or is it the new operator that allocates memory and enables to invoke the constructor to initialize the allocated variable in memory?
To my understanding, you cannot call an constructor of any type without the new operator. Am I correct?
Does declaration in c# allocate memory for the variable to be created or is it the new operator that allocates memory and enables to invoke the instructor to initialize the allocated variable in memory?
First let's make sure that you're asking the question you think you're asking. For a value type, the variable storage location and the value storage location are the same storage. For a reference type, the storage location associated with the variable contains a reference to the storage location associated with the object. Those are completely different.
Second, let's clarify what you mean by "declaration" of a "variable". A static field, an instance field, a local variable and a formal parameter all have declarations. Moreover, the allocation semantics of local variables and formal parameters are different if they are closed-over outer locals of a lambda, and the semantics are also different when the local is in an async method or iterator block.
So let's assume that you have a local variable of reference type and there is nothing fancy about the local:
void M() {
Animal x = new Giraffe(); ...
The storage location for the local variable x is allocated off of the short-term storage -- the stack, or a register, typically -- when method M() is activated.
When the "new Giraffe()" is evaluated the runtime allocates memory for a Giraffe on the long-term storage -- the GC heap -- and then passes a reference to that object to the constructor. When the constructor returns, the reference is then assigned to the local.
So there are two storage locations. There's the short-term location for x, which only lives as long as the activation of the method, and there's the long-term storage for the thing that is referred to, and that lives until the garbage collector cleans it up.
If that doesn't answer your question, clarify your question.
Can you call a constructor without the new operator?
I'm assuming that by "constructor" you mean an instance constructor and not a static constructor.
Not by any "normal" means, no.
declaration without specification allocates memory for (object)null in C#...
string x;
// x = null in memory
string x = "";
// x = string in memory with value.
MyObjectType x;
// x = null;
MyObjectType x = new MyObjectType();
// x = MyObjectType in memory.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With