O'Reilly logo

Professional .NET 2.0 Generics by Tod Golding

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

10.8. The Kitchen Sink

In addition to the guidelines discussed previously, a handful of items also exist that don't necessarily fit into any specific categories. The items that appear in the sections that follow fall into this grab bag of miscellaneous items.

10.8.1. Item 19: Use Static Data Members with Caution

Outside of generics, the behavior of static data members is well understood. Basically, when a data member is static, this indicates that there is one and only one instance of that data member for all instances of that class. This is where the VB "shared" keyword almost conveys the concept better than "static" in that these members are actually shared by all instances of the class.

With generics, the behavior of static data members may not actually match what you're expecting. Take a look at a small example that illustrates how generics manage static data:

[VB code]
Public Class StaticData(Of T)
    Private Shared _staticData As Int32 = 0

    Public Sub IncrementCount()
        _staticData = _staticData + 1
    End Sub
End Class

Public Sub TestStaticData()
    Dim instance1 As New StaticData(Of String)()
    instance1.IncrementCount()

    Dim instance2 As New StaticData(Of Int32)()
    instance2.IncrementCount()

    Dim instance3 As New StaticData(Of String)()
    instance3.IncrementCount()
End Sub
[C# code]
public class StaticData<T> {
    private static int _staticData = 0;

    public void IncrementCount() {
        _staticData++;
    }
}
public void TestStaticData() { StaticData<String> instance1 = new StaticData<String>(); instance1.IncrementCount(); ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required