Le réseau pour les développeurs > Forums - Accueil > Visual C# General > Referencing to Objects from Other Object
Poser une questionPoser une question
 

TraitéeReferencing to Objects from Other Object

  • mercredi 4 novembre 2009 18:17Kikeman Médailles de l'utilisateurMédailles de l'utilisateurMédailles de l'utilisateurMédailles de l'utilisateurMédailles de l'utilisateur
     
    Hi, I am kind of new using C#, I am a programmer from C++.

    I know that C# has a garbage collector but I have a question about referencing objects from other objects.

    I have an Object "Car" and other object "Motor", so that:

    public class Car 
    {
       public Motor TheMotor;
       ...
    }
    
    public class Motor
    {
       public Car TheCarForThisMotor;
       ...
    }
    

    When I start my application these objects are created and assigned:

    Car TheCar = new Car();
    TheCar.TheMotor = new Motor();
    TheCar.TheMotor.TheCarForThisMotor = TheCar;
    

    Later on in the application I need to update (upgrade) the Motor object of the car, so that, I got a new Motor:

    void program_event 
    {
    
    //got a better Motor:
    Motor SuperMotor = new Motor();
    
    TheCar.Motor = SuperMotor; //What happen with the "old motor"?
    SuperMotor.TheCarForThisMotor = TheCar;  //What happen with the reference of the "old motor" to the car
    
    }
    

    Question:
    I am overwriting the value of the TheCar.Motor with other object and also the "old motor" was making a reference of the TheCar (TheCarForThisMotor).

    What happen in this case, the garbage collector would take care of the "old motor"? What happen with the reference to the original car object (does it still exist?)? 
    Should I get firts the old motor and assign null to TheCarForThisMotor?:

    Motor OldMotor = TheCar.Motor;
    OldMotor = null;
    
    //got a better Motor:
    Motor SuperMotor = new Motor();
    
    TheCar.Motor = SuperMotor;
    SuperMotor.TheCarForThisMotor = TheCar
    

    Thanks,
    kikeman.


Réponses

Toutes les réponses