If you don't wish to
declare a Class
as Static, but you want to make a Class that c
annot have instances of it created using 'new, and that cannot be inherited from: that can be done like this:
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:
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: [
^]