Reputation: 59
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?
Upvotes: 3
Views: 599
Reputation: 3457
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.
Upvotes: 8