Tutorial :Activator.CreateInstance - Explain it so I can understand



Question:

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  


Solution:1

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.


Solution:2

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


Note:If u also have question or solution just comment us below or mail us on toontricks1994@gmail.com
Previous
Next Post »