Static Members


A static field is instantiated only once for all objects of the type. A static field is instantiated once for the class. C# and C++/CLI both use the static keyword; Visual Basic offers the same functionality with the Shared keyword.

Using static members is done by using the name of the class followed by the . operator and the name of the static member. C++/CLI uses the :: operator for accessing static members.

  // C# public class Singleton {    private static SomeData data = null;    public static SomeData GetData()    {       if (data == null)       {          data = new SomeData();       }       return data;    } } // use: SomeData d = Singleton.GetData(); // C++/CLI public ref class Singleton { private:    static SomeData^ hData; public:    static SomeData^ GetData()    {       if (hData == nullptr)       {          hData = gcnew SomeData();       }       return hData;    } }; // use: SomeData^ d = Singleton::GetData(); ' Visual Basic Public Class Singleton    Private Shared data As SomeData    Public Shared Function GetData() As SomeData       If data is Nothing Then          data = new SomeData()       End If       Return data    End Function End Class ' Use: Dim d as SomeData = Singleton.GetData() 




Professional C# 2005 with .NET 3.0
Professional C# 2005 with .NET 3.0
ISBN: 470124725
EAN: N/A
Year: 2007
Pages: 427

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net