Reputation: 5455
I was considering using a struct to store several bits of state inside a method, however I wanted to be able to pass this to a helper method using the ref
keword to avoid passing by value. If I do that however, will then be stored on the heap, rather than the stack?
example code:
var link = new Geoff("Bergen");
Perambulate(ref link);
Console.WriteLine(link.Name);
void Perambulate(ref Geoff man)
{
Console.WriteLine("Perambulating {0}",man.Name);
}
struct Geoff
{
public readonly string Name;
public Geoff(string name)
{
Name = name;
}
}
I guess I'm really asking if the ref
keyword forces the referenced value to be stored on the heap.
Upvotes: 3
Views: 87
Reputation: 1042
What you are referring to is called boxing and no, boxing doesn't occur when passing a value type by reference. It'll just pass the reference to Geoff on the stack.
Boxing can happen when casting a value type to a reference type (implicitly as well as explicitly). E.g.:
var g = new Geoff(); //value type
List<object> objects = new List<object>(); //collection of objects (reference type)
objects.Add(g); //implicitly casting g to object
This will cause the Geoff instance to be copied to the heap, which is called boxing.
Now if your Perambulate method accepted an object as a parameter, your passed Geoff would be boxed and copied to the heap.
Upvotes: 2
Reputation: 1677
No it wouldn't. Your struct is already on the stack. It won't be moved to the heap just because you've passed its reference to some method.
Your Perambulate method just receives a references (i.e. an address) to your struct which is stored on the stack.
Upvotes: 0
Reputation: 43254
No it wouldn't be stored on the heap. It would just pass the reference to its location on the stack.
Also, your struct design is not good as you are allowing Name to be changed. The contents of a structure should be immutable. I'd suggest you use a class in this example.
Upvotes: 5