Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# Dictionary unexpectedly returning null

Let's say I have this code:

public static class Converters {
  public static Dictionary<Unit, Dictionary<string, Func<float, float>>> ConverterDictionary =
    new Dictionary<Unit, Dictionary<string, Func<float, float>>> 
    {
        {
            Unit.MS, new Dictionary<string, Func<float, float>>() {
                {"m/s -> km/h", MStoKMH },
                {"m/s -> mph", MStoMPH }
            }
        }
    };

    private static Func<float, float> MStoKMH = val => val * 3.6f;
    private static Func<float, float> MStoMPH = val => val * 2.23693629f;
}

public enum Unit {
    MS
}

And I somewhere else try to retrieve the MStoKMH function from the ConverterDictionary (and invoke it) using this code:

Func<float, float> test = Converters.ConverterDictionary[Unit.MS]["m/s -> km/h"];
float x = test(5);

but the last line throws a NPE ("test was null"). Why my code fails to retrieve the MStoKMH function?

like image 374
anuar2k Avatar asked Mar 12 '26 23:03

anuar2k


1 Answers

Declare the MStoKMH and MStoMPH variables first.

They're initialized in order when they're all Static like this. So at the point you create the dictionary, those variables are still null.

From 10.5.5 of the C# Specification:

Thus, when a class is initialized, all static fields in that class are first initialized to their default values, and then the static field initializers are executed in textual order.

like image 176
Josh Avatar answered Mar 14 '26 12:03

Josh



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!