Reputation: 32374
I am on my mobile phone, so I can't test for myself. Also, I might miss something.
I know that when a number is being assigned, say a = b, b is actually copied into a. But, if b was an object, just a reference wouls be passed. What with other types? Is there something I should worry about?
Also, I heard that you can't use pointers in C# because variables get moved around by the JC. Is it the same in Javascript? How are these references solved in these languages then?
Upvotes: 0
Views: 70
Reputation: 3426
javascript According to specification, you have types: undefined, null, boolean, string, number, object. You can think of them as immutable except object, which is practically just a (hash)map. So yes, if you assign variable, it's "copied" (you don't care if it really is) unless it's an object type. Take example:
var x = "hello";
var y = x; //copy or reference, who cares?
x += " world"; //new string object, x references it
alert(y); //alerts hello
C# According to C# 2.0 specification, there are struct/value types and class/reference types. So, from practical point of view, variable of value type actually stores the data on the call stack (and gets copied on assignment), and variable of reference types is just a reference (and data goes to heap). Example:
int holds_a_value = 5;
StringBuilder holds_a_reference = new StringBuilder();
You can use pointers in C# (pointer = reference), but you have to pin them if you call unsafe functions outside .net / C#, or using unsafe code. e.g.:
fixed (int* p = something) { /*p is safe to use, memory doesn't move */}
Upvotes: 1