Of course the problem with this is that it it is not thread safe.  You could
go with a hybrid:

 public sealed class Singleton
 {
     private static Singleton TheSingleton = new Singleton();
     public static Singleton Singleton
     {
         get { return sobjSingleton; }
     }

     private Singleton()
     {
     }
 }

This doesn't have the on-demand property you require of course.  But it is
nice and simple, and doesn't suffer from the public field problem.

--
Ian Griffiths
DevelopMentor

----- Original Message -----
From: "Stefan Holdermans" <[EMAIL PROTECTED]>


> Just to come up with a good reason to go for
>
> public sealed class Singleton
> {
>     private static Singleton sobjSingleton;
>
>     public static Singleton GetSingleton
>     {
>         if (sobjSingleton == null)
>             sobjSingleton = new Singleton();
>
>         return sobjSingleton;
>     }
>
>     private Singleton()
>     {
>     }
> }
>
> instead of the shorter
>
> public sealed class Singleton
> {
>     public static Singleton TheSingleton = new Singleton();
>
>     private Singleton()
>     {
>     }
> }
>
> The latter uses a public static field: we don't like to use these.
>
> But more important: the first approach creates the singleton instance on
> demand. The second approach just creates the instance, even if it isn't
> needed throughout the life of an AppDomain. Often singetons are
> issued 'heavy' objects: recall the in-memory database mentioned earlier in
> this thread. You typically don't want these big things created when you
> don't really need them.
>
> P.S. A last note on the sealed modifier that --- appearently --- seems so
> natural to us on singleton classes: consider singletons you can inherit
> from. Think of cases where you want only one instance for each sub class
> to be created.

You can read messages from the Advanced DOTNET archive, unsubscribe from Advanced 
DOTNET, or
subscribe to other DevelopMentor lists at http://discuss.develop.com.

Reply via email to