Neat trick for C# coders

Sometimes you need a semi-constant.

Now what is a semi constant, something that changes very infrequently.

Often the calculation for these values is very expensive, so you do not want to calculate it every frame. That’s just burning CPU for no good reason.

To give an example. Suppose you are writing a space game where you can travel through many solar systems. You will have many different types of stars and will want to change the games illumination to reflect the colour of the light emitted by the star. Now the formula for this is well documented all over the internet, and you could just pick a subset of stars and stick them in an array. Or you could calculate the light colour when you enter a solar system and store it.

In these cases I use a neat trick. Nullable types.

When you need a value to be recalculated, you null it and the next time you do a get, this is detected and the value recalculated.

For example.

public static Vector3 ExtraterrestrialSunlight
            if (!_extraterrestrialSunlight.HasValue)
                Vector3 sunlightXyz = spectrum.ToXYZ();
                Vector3 sunlightRgb = XYZToRGB * sunlightXyz;
                _extraterrestrialSunlight = sunlightRgb;

            return _extraterrestrialSunlight.Value;
    private static Vector3? _extraterrestrialSunlight;


Now why do I like this technique?

I write very heavily multi-threaded code. Sometimes I have absolutely no idea which code block will be executed first. In some cases the execution order will vary over time.

With this technique I KNOW the value will be correct when it is needed and I know the expensive calculation will only happen once.

So for me this is a go to technique.

Hope this little trick is useful.