I've been thinking on how the memory would be handled in some specific case which i'll explain (C# 4.0).
To begin with, i've read Eric Lippert answer in order to know what will be invoked whenever I use new on a variable of type struct
And now, I wonder if the compiler "produces" intelligent code in specific use of the new keyword
To be precise, what will it do if the new is set on a return instruction or even on operator = ?
Assume we have a struct Coord defined as follow:
struct Coord {
int x, y;
public Coord(int xx, int yy) {
x = xx;
y = yy;
}
}
I'll use this struct to store position and velocity in classes (suppose we call them Entity) that have geometric behaviors
Entity is defined as follow:
class Entity {
private Coord m_pos, m_vel;
//...
public Entity() {
// ...
}
public Coord Position {
get {
return m_pos;
}
set {
m_pos = value;
}
}
public Coord Velocity {
get {
return m_vel;
}
set {
m_vel = value;
}
}
}
My main program contains a routine which simply update my entities (and so their position and velocity as well)
Now my question is : What's the price, if I decide to update these 2 members by using new on it:
Entity a; // initialized
...
private Coord getNewPosOf(Entity e) {
...
return new Coord(computed_x, computed_y);
}
public void routine() {
a.Velocity = new Coord(x_vel, y_vel);
a.Position = getNewPosOf(a);
}
Will that code allocate memory in the short-term storage and therefore also copy values from the constructor to the memory location of a. Or will the compiler take care of things and avoid allocating and copying memory in that specific case?
Note: I have the feeling i'm doings things wrong, maybe I should not be using Properties to edit my Coord-type members (or worst, I may not use Properties correctly and there is another way to do what I want)