Click here to Skip to main content
15,896,269 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hi Every one,
Is it possible to create a single class instance without using any static options in the class.

Regards,
Arun R.V
Posted
Comments
PIEBALDconsult 24-Nov-14 9:40am    
Maybe use a Mutex, but it's not a worthwhile goal.

If you don't wish to declare a Class as Static, but you want to make a Class that cannot have instances of it created using 'new, and that cannot be inherited from: that can be done like this:
C#
sealed class MyMathFunctions
{
    private MyMathFunctions() { }

    private const double PI = 3.14159265358979323846;

    public static double MyFunction1(int x, int y)
    {
        return 2 * PI * Math.Sqrt((x ^ 2) + (y ^ 2));
    }
}
Here the private constructor prevents instantiation, and declaring the Class as 'sealed prevents inheriting from it. But, to get access to any element inside this Class ... like, in the example here the function MyFunction1 ... you must declare the element as 'static.

If all you want to implement is a some kind of resource library you could use this kind of declaration/structure: but, why would you ? Why not just go ahead and use a fully static Class:
C#
public static class MyMathFunctions
{
    private const double PI = 3.14159265358979323846;

    public static double MyFunction1(int x, int y)
    {
        return 2 * PI * Math.Sqrt((x ^ 2) + (y ^ 2));
    }
}
But, beyond these two choices is the idea of using a true "Singleton" which gives you encapsulation (no creation with 'new, no inheritance from if it is 'sealed), and a range of other functionality such as: >[^].

Here's Jon Skeet's brief comment on Singleton vs. static Class, quoted in a long thread on StackOverFlow that's well worth reading:
"A singleton allows access to a single created instance - that instance (or rather, a reference to that instance) can be passed as a parameter to other methods, and treated as a normal object. A static class allows only static methods"
[^].

There are many ideas about how implement a Singleton, depending on issues like thread safety, desirability of "lazy loading," etc., and frequent debate about the cost/benefits of different ways of doing this, but all (to my knowledge) require a static instance variable in the Class of the Class itself, and a private parameterless constructor.

And, your Singleton Class can inherit from Interfaces and another Class: the static Class cannot.

Here's some other suggested reading to expose you to the use of Singletons in C#:

The DoFactory, publishers of (commercial) design-pattern code for .NET, has a good page (no cost) with code examples on different Singleton strategies in .NET: [^]. Disclaimer: while I did purchase their product, I have no relationship with the company other than being a happy customer.

Another SO thread: "On Design Patterns: When to use the Singleton?" [^].

Advanced, and a challening viewpoint: [^]
 
Share this answer
 
v3
Comments
Afzaal Ahmad Zeeshan 24-Nov-14 16:25pm    
A well written answer Bill, I came to learn about how to not let instantiate any class by your answer - setting its constructor as private, and many more things. Also, a good point mentioning Jon Skeet's post, he's a genius in C#, atleast as far as I have talked to him on Stack Overflow. +5
BillWoodruff 24-Nov-14 16:45pm    
Jon Skeet is definitely an "experts' expert;" I think there are very few at his level of understanding and ability to communicate.

One of the pleasures of studying the book "The C# Programming Language" by Hejlsberg, Torgersen, Wiltamuth, and Golde, are the frequent comments inserted as call-outs in the text by Skeet, and by others including Eric Lippert, Brad Abrams, Jesse Liberty, Chris Sells, and other experts. Those guys don't pull any punches.

http://www.amazon.com/Programming-Language-Covering-Microsoft-Development/dp/0321741765
ISBN-13: 978-0-321-74176-9
ISBN-10: 0-321-74176-5

CodeProject has its share of really expert C# programmers, too (I'm not one, and will never be one), Sacha Barber, OriginalGriff, Sergey Kryukov [if you can survive the dragons at the mouth of his cave :)], Pete O'Hanlon, and many others.
Afzaal Ahmad Zeeshan 25-Nov-14 3:26am    
Yeah, he really is the best guy in this field - when I talked to him a bunch of a time, it was like I'm talking to more like a friend. His way of teaching and helping is a great way nubes get his points easily.

As far as Sergey is concerned, he is really a great guy and if that dragon wasn't there, most of us here would have slipped away from the concept of perfect answer. He really helps others on their and rewards them if they're onto it!
As I saw many implementation of the singleton, let me point out a good one:
http://csharpindepth.com/Articles/General/Singleton.aspx[^].

Note that there is usually a way to work without singletons, and the singletons can be potentially dangerous, especially in multithreaded programming. In practice, they can be used, but it would be quite bad to overuse them.

—SA
 
Share this answer
 
v2
Comments
Maciej Los 24-Nov-14 10:58am    
I was wondering your answer, Sergey, but one sentence?
+5 for link!
Sergey Alexandrovich Kryukov 24-Nov-14 11:21am    
Thank you, Maciej.
—SA
Afzaal Ahmad Zeeshan 24-Nov-14 16:24pm    
Short but good answer Sergey - my 5.
Sergey Alexandrovich Kryukov 24-Nov-14 16:53pm    
Thank you, Afzaal.
—SA
In order to keep the count of existing instances you need to use a variable shared among the instances hence it is natural the use of a static member, in my opinion there no reason against it.
 
Share this answer
 
This would help you Implementing Singleton in C#

Do not forget to use double NULL check (before and after lock statement) in case using it with multiple threads.
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900