Static members in VB.NET

I wrote this:

Private Sub Example() Static CachedPeople As List(Of MyApp.Person) If CachedPeople Is Nothing Then CachedPeople = New List(Of MyApp.Person) End If ...rest of code... End Sub 

But then I thought if I could reduce this:

 Private Sub Example() Static CachedPeople As New List(Of MyApp.Person) ...rest of code... End Sub 

The question is whether the β€œNew” bit will be launched only once, when the function is first executed, but in the next call it will already exist.

Greetings Rob.

+4
source share
1 answer

It will be executed only once and the next time the function is called, it will refer to the same object as you mentioned. By the way, your first fragment is not thread safe. If two threads call your function at the same time, they may end up running the constructor twice, which you don't want. Using the second fragment frees you from manually blocking and ensuring thread safety, since the compiler creates the appropriate code for you.

Please note that if you declared it as

 Static x As List(Of String) x = New List(Of String) 

It was recreated every time.

+9
source

All Articles