Search code examples
c#constructorgarbage-collectiondestroy

Destroy objects per instance


There are several much more complicated answers out there to a simple question I have, so I'll ask the question in regards to my situation because i can't quite figure out what to do based off of those other answers. Garbage collection seems like a danger zone, so I'll err on the side of caution.

I have a Measurement object that contains a Volume object and a Weight object. Depending on which constructor is used, I would like to destroy the opposite object, that is to say, if a user adds a volumetric measurement, I would like to eradicate the weight element of that instance, as it is just bloat at that point. What should be done?

Edited for clarification:

public class RawIngredient
{
    public string name { get; set; }
    public Measurement measurement;

    public RawIngredient(string n, double d, Measurement.VolumeUnits unit)
    {
        name = n;
        measurement.volume.amount = (decimal)d;
        measurement.volume.unit = unit;

        //I want to get rid of the weight object on this instance of measurement
    }

    public RawIngredient(string n, double d, Measurement.WeightUnits unit)
    {
        name = n;
        measurement.weight.amount = (decimal)d;
        measurement.weight.unit = unit;

        //I want to get rid of the volume object on this instance of measurement
    }
}

Edited again to show Measurement

public class Measurement
{

    public enum VolumeUnits { tsp, Tbsp, oz, cup, qt, gal }
    public enum WeightUnits { oz, lb }

    public Volume volume;
    public Weight weight;
}

Volume and Weight are simple classes with two fields.


Solution

  • If you are in the Measurement constructor, then simply don't create the non-required type; it will remain as the default value of null (as long as Volume and Weight are reference types and not structs), and any attempted reference to the wrong type would throw an exception.

    As long as the Measurement object is in scope, the garbage collector couldn't collect the non-required type, as it would be in the scope of the Measurement instance, and could theoretically be created at any time, regardless of your actual intentions in reality.