15.02.2015 Views

C# 4 and .NET 4

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

OC170 ❘ ChaPTer 53 c#, visuAl bAsic, c++/cli, And f#<br />

// <strong>C#</strong><br />

public class Singleton<br />

{<br />

private static SomeData data = null;<br />

public static SomeData GetData()<br />

{<br />

if (data == null)<br />

{<br />

data = new SomeData();<br />

}<br />

return data;<br />

}<br />

}<br />

// use:<br />

SomeData d = Singleton.GetData();<br />

code snippet CSharp/Singleton.cs<br />

// C++/CLI<br />

public ref class Singleton<br />

{<br />

private:<br />

static SomeData^ hData;<br />

public:<br />

static SomeData^ GetData()<br />

{<br />

if (hData == nullptr)<br />

{<br />

hData = gcnew SomeData();<br />

}<br />

return hData;<br />

}<br />

};<br />

// use:<br />

SomeData^ d = Singleton::GetData();<br />

code snippet CPPCLI/Singleton.h<br />

' Visual Basic<br />

Public Class Singleton<br />

Private Shared data As SomeData<br />

Public Shared Function GetData() As SomeData<br />

If data is Nothing Then<br />

data = new SomeData()<br />

End If<br />

Return data<br />

End Function<br />

End Class<br />

' Use:<br />

Dim d as SomeData = Singleton.GetData()<br />

code snippet VisualBasic/Singleton.fs<br />

arrays<br />

Arrays are discussed in Chapter 6, “Arrays <strong>and</strong> Tuples.” The Array class is always behind the scenes of<br />

.<strong>NET</strong> arrays; declaring an array, the compiler creates a class that derives from the Array base class. When<br />

<strong>C#</strong> was designed, the designers of the <strong>C#</strong> language took the bracket syntax for arrays from C++ <strong>and</strong><br />

extended it with array initializers:<br />

// <strong>C#</strong><br />

int[] arr1 = new int[3] {1, 2, 3};<br />

int[] arr2 = {1, 2, 3};<br />

www.it-ebooks.info

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!