Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 7712095
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: June 1, 20262026-06-01T01:32:32+00:00 2026-06-01T01:32:32+00:00

I have the following code implementation of my generic singleton provider: public sealed class

  • 0

I have the following code implementation of my generic singleton provider:

public sealed class Singleton<T> where T : class, new()
{
     Singleton()
     {
     }

     public static T Instance
     {
          get { return SingletonCreator.instance; }
     }

     class SingletonCreator
     {
          static SingletonCreator()
          {
          }

          internal static readonly T instance = new T();
     }
}

This sample was taken from 2 articles and I merged the code to get me what I wanted:

http://www.yoda.arachsys.com/csharp/singleton.html and
http://www.codeproject.com/Articles/11111/Generic-Singleton-Provider.

This is how I tried to use the code above:

public class MyClass
{
     public static IMyInterface Initialize()
     {
          if (Singleton<IMyInterface>.Instance == null  // Error 1
          {
               Singleton<IMyInterface>.Instance = CreateEngineInstance();  // Error 2
               Singleton<IMyInterface>.Instance.Initialize();
          }

          return Singleton<IMyInterface>.Instance;
     }
}

And the interface:

public interface IMyInterface
{
}

The error at Error 1 is:

'MyProject.IMyInterace' must be a non-abstract type with a public parameterless constructor in order to use it as parameter 'T' in the generic type or method 'MyProject.Singleton<T>'

The error at Error 2 is:

Property or indexer 'MyProject.Singleton<MyProject.IMyInterface>.Instance' cannot be assigned to -- it is read only

How can I fix this so that it is in line with the 2 articles mentioned above? Any other ideas or suggestions are appreciated.

Does my implementation break the Singleton pattern?

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-06-01T01:32:33+00:00Added an answer on June 1, 2026 at 1:32 am

    Basically, you’ve given a class constraint on your singleton class, along with the new() constraint.

    When writing

    Singleton<IMyInterface>
    

    you’re using an interface type as T, which violates the type constraint you defined.

    For error 2,

    Singleton<IMyInterface>.Instance = CreateEngineInstance();
    

    you’re trying to assign a value to a read-only property. So you need to define a setter on your Instance property for that line to work.

    Update

    Something along these lines should do it for you :

    public sealed class Singleton
    {
         private static Hashtable bindings = new Hashtable();
         private static Hashtable instances = new Hashtable();
    
         private static void checkType(Type requested, Type bound)
         {
            if (requested.IsValueType)
                throw new Exception("Cannot bind a value type to a reference type");
    
            // also check type inheritance and other things...
         }
    
         private static void checkBinding(Type requested)
         {
            if (!(bindings.ContainsKey(requested)))
                throw new Exception(String.Format("Type {0} was not bound !", requested.FullName));
         }
    
         public static void Bind<T, U>() where U : class, new() 
         {
            checkType(typeof(T), typeof(U));
            bindings[typeof(T)] = typeof(U);
         }
    
         public static T GetInstance<T>() 
         {
            Type requested = typeof(T);
            Type bound = (Type) bindings[requested];
    
            checkBinding(requested);
    
            if (!instances.ContainsKey(requested)) {
                // We know that type "bound" was set with a new() class constraint
                instances[requested] = (T) Activator.CreateInstance(bound);
            }
    
            return (T) instances[requested];
         }
    }
    

    You could then write :

     Singleton.Bind<IMyInterface, MyClass>();
     IMyInterface instance = Singleton.GetInstance<IMyInterface>();
    

    If you want to go further, you could also specify the lifecycle of the objects created by this provider, so that you could use singletons, or have the provider return a new object for each call, and so on.

    You should also take a look at the Dependency Injection pattern, which seems close to what you want achieve, and also look at existing DI frameworks (NInject, Nhibernate) that already do this and much more.

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I have the following code for factory design pattern implementation. class Pen{ public: virtual
I Have following code: Controller: public ActionResult Step1() { return View(); } [AcceptVerbs(HttpVerbs.Post)] public
I have following code class User attr_accessor :name end u = User.new u.name =
Basically, I have the following code: public class MyDictionary<TKey, TValue> : IDictionary<TKey, TValue> {
I have the following code to my UIViewController class implementation: - (void)viewDidLoad { CustomUITableView
I have the following code inside my @interface FriendsNavController : UINavigationController class implementation. The
I have following code snippet that i use to compile class at the run
I have following method in my Borland C++ code, static bool UploadBitstream(void) { //Some
Have the following code: #import UsingViewsViewController.h @implementation UsingViewsViewController @synthesize pageControl; @synthesize imageView1, imageView2; -
I have the following code public ClassToTest : IClassToTest { private readonly DBRepository rep;

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.