Don’t put static members on generic classes…unless you mean to!

This bears repeating even if you’ve heard it before, but static members don’t *appear* to behave like regular static members when they’re located on a generic class. This is usually a result of the developer’s lack of understanding of how the compiler deals with generics. If you create Foo<T> and in your code create instances of Foo<int> and Foo<string>, the resulting instances of Foo<int> will share one set of static members, while Foo<string> will share another. That’s because under the hood the compiler is creating a separate class for each generic type combo your code creates. Someone on my team refactored a class that had static members to use generics and didn’t realize this, which led to weird craziness at runtime 😉

Advertisements
This entry was posted in Coding and tagged . Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s