The dangers of static members
December 14th, 2008 — 04:30 pm(If you use Visual Studio 2003 or you tend to ignore compiler warnings, this post is for you)
Static classes and members have their uses. However, I recently encountered a dangerous pitfall regarding their usage.
Consider the following code:
public static class MyClass
{
public static int myVal = MyClass.myVal;
public static MyOtherClass myClass = MyClass.myClass;
public static Color myColor = MyClass.myColor;
}
Can you spot what is wrong here?
You got it right - this class assign it’s members back to themselves, effectively avoiding assigning them.
If you try using this code using VS2003 it will compile without any notification. In more recent version you’ll only get a compiler warning.
What’s worse yet: you can make the member private and the code would still compile.
But it can get even worse:
Since these members are not assigned, with value types you’ll get the default value, while with most classes you’ll have a null reference.
But the Color struct is something different. It retains an Empty value, and if your winform application uses the default theme and colors, assigning an empty color to a control basically does nothing.
Now try understanding why your panel refuses to change color….