Question

I know the general difference between value type and reference type, and I also know when using a value type in a reference type, this value type is actually on the heap.

ex:

class ClassA{
   public DateTime date1 = new DateTime(2008, 3, 1, 7, 0, 0);
}

when

ClassA a = new ClassA();

the date1 is on heap

My question is

if we use this date1 as a parameter in a method, what's the memory location behavior?

public void methodA(DateTime dt)
{
//do sth with the dt
}

invoke the method

methodA(new ClassA().date1);

Option 1: Just copies one date1 reference Option 2: Or copy date1 data to run

UPDATE: After reading the "the truth about value types", i realised there are some uncertainties in my assumption. At least I should give a context like. "in the Microsoft implementation of C# on the desktop CLR, value types are stored on the stack when the value is a local variable or temporary that is not a closed-over local variable of a lambda or anonymous method, and the method body is not an iterator block, and the jitter chooses to not enregister the value."

Update2: The reason I asked about this is I want to understand some code snippet on http://marcgravell.blogspot.co.uk/2011/10/assault-by-gc.html

change Customer from a class to a struct (only within this crazy code)

change the main store from a List to a Customer[]

change the subsets from List to List, specifically the offset intothe main Customer[]

void SomethingComplex(ref Customer customer) {...}
...
int custIndex = ...
SomethingComplex(ref customers[custIndex]);
Was it helpful?

Solution

DateTime is a value type, so the value will be copied on method invocation.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top