Singleton example 2

How do I call an instance of this class using C# in Visual Studio 2017?  At the moment I have a console App.  In the static main method I have this code, but can't invoke the Inventory class due to its protection level.

static void Main(string[] args)
        {
            Inventory I1 = new Inventory();
        }

Open in new window


I've seen a similar question here, but I want to understand what's happening rather than just copy and paste https://www.experts-exchange.com/questions/21783726/Singleton-example.html
I'd like to see the class invoked successfully once then produce an error message when I try to invoke it a second time.

    private static readonly Lazy<Inventory> instance = new Lazy<Inventory>(() => new Inventory());
    private Inventory()
    { }
    public static Inventory Instance
    {
        get { return instance.Value; }
    }
    public void LookupProduct(string upc)
    {

    }

Open in new window

AlHal2Asked:
Who is Participating?
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

AndyAinscowFreelance programmer / ConsultantCommented:
>>I'd like to see the class invoked successfully once then produce an error message when I try to invoke it a second time.

That is rather an odd requirement.  Why?  It sort of defeats the purpose of having a singleton.

A Singleton is designed so there is only one instance possible.  The constructor is coded to prevent a user trying to use the new keyword to make two or more instances.
One uses a singleton as follows for example

Inventory inv = Inventory.Instance;

or
Inventory.Instance.SomeFunctionOrMethod();
AlHal2Author Commented:
Should this not produce an error as its invoking it twice?

            Inventory inv = Inventory.Instance;
            Inventory inv2 = Inventory.Instance;

Open in new window

Could you show me how to use the new keyword once to make one instance?
AndyAinscowFreelance programmer / ConsultantCommented:
You don't seem to understand what the static keyword is.

It is only having one instance. inv and inv2 are actually identical.  

>>Could you show me how to use the new keyword once to make one instance?
Something like this is required.  (Just out of my head, may need mods to compile but you should see the idea).

public class OnceOnly
{
private static bool bIsCreated = false;
public OnceOnly()
{
if(bIsCreated)  throw new Exception("Already Created");
bIsCreated = true;
}
}
PMI ACP® Project Management

Prepare for the PMI Agile Certified Practitioner (PMI-ACP)® exam, which formally recognizes your knowledge of agile principles and your skill with agile techniques.

AndyAinscowFreelance programmer / ConsultantCommented:
Note with something like that code snippet (for OnceOnly) you can only create one instance ever in the program, even after the one you create is destroyed.  To only allow one instance at any one time is rather more complex with .net and garbage collection.
AndyAinscowFreelance programmer / ConsultantCommented:
ps.  The code for OnceOnly doesn't really stop a second instance being created, it does give you a pretty strong warning and will only stop you using a second instance under certain circumstances.  It can be got around.  A really robust method is much more complex.
AlHal2Author Commented:
Would you have any code samples eg to stop a program invoking more than one instance of a print queue at a time or log file generator.  For example could the code at the bottom of this article be converted to C#
https://dzone.com/articles/singleton-design-pattern-%E2%80%93
AndyAinscowFreelance programmer / ConsultantCommented:
To have one common instance for eg. printing or logging you should use a singleton.

You use a singleton as I indicated in my first comment:
Inventory inv = Inventory.Instance;
or
Inventory.Instance.SomeFunctionOrMethod();

You do NOT use the new keyword to create an instance of a singleton in your code.  The code you supplied in your question is one way to create a singleton class.

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
AndyAinscowFreelance programmer / ConsultantCommented:
AlHal2Author Commented:
Thanks.  I'll try and find some examples online and come back to you with any further questions.
AndyAinscowFreelance programmer / ConsultantCommented:
Read up about the static keyword, things should become a lot clearer when you understand what that is doing.
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
C#

From novice to tech pro — start learning today.