Kjensen
Kjensen

Reputation: 12374

Activator.CreateInstance - Explain it so I can understand

So I am looking at some sample code, and I am not sure what to make of this:

    Private Shared _instance As PollsProvider = Nothing

    Public Shared ReadOnly Property Instance() As PollsProvider
        Get
            If IsNothing(_instance) Then
                _instance = CType(Activator.CreateInstance( _
                    Type.GetType(Globals.Settings.Polls.ProviderType)), PollsProvider)
            End If
            Return _instance
        End Get
    End Property

What is the difference between the above and how I would normally make a singleton:

    Private Shared _instance As PollsProvider = Nothing

    Public Shared ReadOnly Property Instance() As PollsProvider
        Get
            If IsNothing(_instance) Then
                _instance = New PollsProvider
            End If
            Return _instance
        End Get
    End Property

Upvotes: 0

Views: 813

Answers (2)

RS Conley
RS Conley

Reputation: 7196

itowlson got it right. I will add it looks like PollsProvider probably a interface or a class that other classes inherit from.

Upvotes: 0

itowlson
itowlson

Reputation: 74802

The first code fragment reads the type of PollsProvider to create from config, whereas the second has the type of PollsProvider compiled in. The first fragment therefore allows you to switch in configuration (without a recompile/redeploy) between RealPollsProvider, TestPollsProvider, FiddledByOurEvilPaymastersPollsProvider, etc.

Upvotes: 5

Related Questions