|
I've just started learning C# yesterday, and I'm really confused with the reference system.
Can anyone please help explain to me what would happen here:
class Population{
public void DuplicatePopulation(Population thatPop){
x=thatPop.x;
}
public int x;
};
class GA{
public GA(){
InitPop=new Population();
CrossOverPop=new Population();
}
public Population FindPopID(int ID){
switch(ID){
case 1:return InitalPop;break;
case 2:return CrossOverPop;break;
default:break;
}
return InitialPop;
}
public void DuplicatePopulation(int FromID,int ToID){
Population FROM,TO;
FROM=FindPopID(FromID);
TO=FindPopID(ToID);
TO.DuplicatePopulation(FROM);
}
Population InitialPop,CrossOverPop;
};
class MainClass{
public void main(string[] args){
GA GeneticAl=new GA();
GeneticAl.DuplicatePopulation(1,2);
};
What I'm trying to do is duplicate population Init to Population CO. With this code, will the value of CrossOverPop.x == InitPop.x
Am I already passing by reference? or did i need to use the ref keyword?
|
|
|
|
|
All objects are inherently reference types i.e. they are passed around by reference.
So you don't need the ref key to pass them around.
|
|
|
|
|
The ref keyword has a special meaning when applied to reference types. When ref is applied to a reference type, you can actually make the variable point to a different object altogether. Passing without the ref keyword (the default) will only allow you to change the state of the object, you cannot make it point to a different object.
|
|
|
|