Static fields are immensely useful things. However, they can also cause a lot of headaches if used without thinking. Due to the JIT compiler's way of not making things until necessary, using static fields to keep important constant references is dangerous, especially when the declaration involves a constructor. I was using something like this to define characters for NetBLAM:
Class Characters
...
Public Shared SidKetchum As Character = New Character(5)
...
End Class
The constructor of Character added it and its ID (the 5) to a static dictionary. However, when I accessed that dictionary, it contained zero entries because none of the fields in Characters had ever been directly accessed and thus threw a NullReferenceException. To solve this situation, I removed the automatic registering from the Character class and had CharacterRegistry (a manager for the in-use characters) add them to the dictionary with reflection in its constructor.
No comments:
Post a Comment