Prevent a Class from being instantiated - c#

Hi i want to have a class that cannot be instantiated but can be added as a static field to another class but i could not achieve it;
Here is what i've done;
public class ValueListManager
{
public static Operations myOps { get { return new Ops(); } }
}
public interface Operations
{
void Call();
}
public class Ops : Operations
{
public void Call()
{
}
}
I dont' want the Ops class to be instantiated anywhere else. Basically I want to be able to;
ValueListManager.Operations.Call();
But i dont want to be able to use the ops class like;
var ops = new Ops();
Is there a way to achieve this?

You can achieve that by declaring the Ops class as a private class within the ValueListManager class where you want to use it:
public class ValueListManager
{
private class Ops : Operations
{
public Ops()
{
}
public void Call()
{
}
}
public static Operations myOps { get { return new Ops(); } }
}
Note, that in this example based on your code, a new instance of the Ops class is created every time you access the myOps property. If you don't want that, you need to store the Ops instance in a static field once it is created and use that in the Getter of the property.

As I understand you want to instantiate this class only once and later use it.
You can use Singletone pattern, you can also use inheritance with this pattern.
public class Ops: Operations
{
private static Ops instance;
private Ops() {}
public static Ops Instance
{
get
{
if (instance == null)
{
instance = new Ops();
}
return instance;
}
}
public void Call()
{
// do something
}
}
and where you want to use it you can call its method:
Ops.Instance.Call()

If you don't want to nest your classes for some reason, and don't want to basically change anything except the Ops class itself, you could put your code into a different assembly (add a class library to your solution), and make the constructor internal:
public class ValueListManager
{
public static Operations myOps { get { return new Ops(); } }
}
public class Ops : Operations
{
internal Ops() {}
public void Call()
{
}
}
Then you'd only need to add a reference to that assembly from the one you want to use that, you'd not need to change any other code.
The constructor (thus new Ops()) can only be accessed from that assembly, code in other assemblies won't be able to new.

This is very similar to the design pattern singleton, but it is unclear from your code if you want only one instance or if you don't want to instantiate it from elsewhere?
If it is a single instance you're after the most recommended way to implement a singleton in c# is using the static constructor:
public class Single
{
private static Single instance;
private Single() { }
static Single()
{
instance = new Single();
}
public static Single Instance
{
get { return instance; }
}
}
Most other ways have (at least a theoretical) risk of threading issues.
However it should be noted that the singleton pattern (and typically extensive use of static methods) is in some contexts an indication of a bad design.

Related

C#: Protected Variables inside of a Generic Class can be accessed by a different subclass of that Generic Class. Can I prevent this?

Say I have a generic class Foo, that has a variable that is protected
public class Foo<T>
{
protected bool knowsFu;
}
I also have 2 sub-classes: Bar and Pipe
public class Bar : Foo<Bar> {}
public class Pipe : Foo<Pipe> {}
It is actually possible for me to access the knowsFu in Pipe FROM Bar, e.g.:
public class Bar : Foo<Bar>
{
void UpdateFuInOtherClass(Pipe p)
{
p.knowsFu = false;
}
}
Is this intended behaviour? (If so, what would be the usecase?)
Is there a way for me to prevent other Foo-Subclasses from modifying/reaching the protected variable inside of my current subclass?
More specifically: I'm using a generic class to implement the Singleton-Pattern:
https://en.wikipedia.org/wiki/Singleton_pattern
However, I'm currently able to access any singleton's protected instance-variable, as long as I am inside of another Singleton. Is there a way to prevent this?
EDIT: It might be relevant to note that the protected variable (knowsFu) is actually STATIC as well.
EDIT2: Ok, maybe the example was abit too generic.. here's how I'm actually currently implementing it:
why use Singleton? A:The platform I'm working on is Unity3D, in which the pattern is used frequently
I have a generically typed abstract class SingletonBehaviour
public abstract class SingletonBehaviour<T> where T : MonoBehaviour
{
public static T Instance { get { return instance; } }
protected static T instance { get; private set; } }
// Loading is done through Unitys Awake-Method
}
One of the Singleton-Objects that I'm using is the APIManager
public class APIManager : SingletonBehaviour<APIManager>
{
// Methods like SendHTTPPost(), HTTPGet(), etc.
}
However, since most of my projects need some better API-implementation than that, what I'm currently doing is:
public class ProjectAAPIManager : APIManager
{
// Overriding Instance so my return value is not APIManager but instead ProjectAAPIManager
public static new ProjectAAPIMamager Instance { get { return (ProjectAAPIManager)instance; } }
}
This ^ is the reason my (inner) instance-variable is protected, and not private.
However, because of this, any other SingletonBehaviour in my project can now access the (inner) instance-variable on my ProjectAAPIManager
public class GameController : SingletonBehaviour<GameController>
{
private void AMethod()
{
// Accessing inner variable instead of public one
ProjectAAPIManager.instance.DoSomething();
}
}
As it's only the getter, this currently does not really matter. But what if I'd need access to the setter in my subclass as well?
Also: would it be worth it to generically type my APIManager as well?
Your question is nothing short of bewildering. How can you make a protected member not be accesible from a derived class? Well, a good start is not making it protected.
protected is by definition exactly what you don't want, so don't use it! Use private instead.
If what you are asking is how to make it a readonly member when accessed from derived types, you have two options:
Declare it as readonly in the base class if possible.
Use a protected property instead with a private setter.
Many novice coders seems to think protected members aren't part of the public surface of the type but they really are, as long as the class can be extended. As such, the rules of public members apply: never expose public fields unless they are readonly or constants, use properties instead.
You should not have classes that implement your generic singleton class.
Otherwise, by default, your protected fields will be accessible by the subclasses (it's what "protected" keyword does)
Instead, you should do something like this:
class Program
{
static void Main(string[] args)
{
var barInstance = Foo<Bar>.GetInstance();
}
}
public class Foo<T> where T : new()
{
protected bool knowsFu;
private static T _instance;
public static T GetInstance()
{
if (_instance == null)
_instance = new T();
return _instance;
}
}
public class Bar
{
public Bar()
{
}
}
Edit 1:
To use a singleton, you should not make another class implement the singleton behavior (This is not how the singleton pattern works).
To use the same classes as your second example, you should do something like this.
public class SingletonBehaviour<T> where T : new()
{
public static T Instance
{
get
{
if(instance == null)
instance = new T()
return instance;
}
}
private static T instance { get; set; }
}
public class APIManager // This class should not inherit from the SingletonBehavior class
{
// Methods like SendHTTPPost(), HTTPGet(), etc.
}
public class ProjectAAPIManager : APIManager
{
public ProjectAAPIManager GetInstance() => SingletonBehavior<ProjectAAPIManager>.Instance();
}

How to ensure only A class can create an A.B instance?

I have a broker class that issues request objects and expects them to be delivered back to it with a couple properties changed to sensible values. The problem is that the consumers of said broker must never change a couple readonly properties of that object nor be able to create a different request instance to cheat that readonly protection or the broker will break and throw an exception. I want to find a way to make the compilation fail if any class save for the broker tries to create a request object.
I think sealing the instantiation of the request objects so it can only be done from inside the broker itself is a neat idea coupled with readonly properties so request processors can never cheat the system but i am having a hard time doing so. I tried a child class with a private constructor like this:
public class PermissionsRequestBroker {
public PermissionsRequest Test() {
return new PermissionsRequest();
}
private class PermissionsRequest {
private PermissionsRequest() {
}
}
}
But it fails because the broker cannot create the request object.
I tried a similar approach but with an interface like this:
public class PermissionsRequestBroker {
public IPermissionsRequest Test() {
return new PermissionsRequest();
}
public interface IPermissionsRequest {
}
private class PermissionsRequest : IPermissionsRequest {
public PermissionsRequest() {
}
}
}
But the request processors can implement IPermissionsRequest and cheat the system that way. Sure i could implement a runtime check so the object returned is still the broker's PermissionRequest object but that's still a runtime check and will throw an exception.
I'm all for exceptions but i feel there must be some way to enforce that contract at compile time without installing any IDE extension or NuGet package of any kind.
Place PermissionsRequestBroker and PermissionsRequest in a separate assembly together, and mark PermissionsRequest as internal instead of public. Then if you need consumers to be able to hold onto an instance of the PermissionsRequest object, wrap it in another class that is public.
Something like the following:
public class PermissionsRequestBroker {
public PermissionsRequestWrapper Test() {
return new PermissionsRequestWrapper( new PermissionsRequest() );
}
}
internal class PermissionsRequest {
internal PermissionsRequest() {
}
}
// Use 'sealed' to prevent others from inheriting from this class
public sealed class PermissionsRequestWrapper {
private PermissionsRequest _permissionsRequest;
internal PermissionsRequestWrapper(PermissionsRequest permissionsRequest) {
_permissionsRequest = permissionsRequest;
}
/* etc... */
}
I know this is already answered, but I'm curious... why wouldn't this work?
EDIT: Had a brain freeze moment, the below code will not work, see the edit after that.
public class PermissionsRequestBroker {
public PermissionsRequest Test() {
return new PermissionsRequest();
}
public sealed class PermissionsRequest {
private PermissionsRequest() {
}
}
}
Basically making the inner class public and sealed but only its constructor private?
EDIT
If we invert this, it would be simpler to implement, thoughts? The staticness of the broker is optional of course.
public class PermissionsRequest
{
private PermissionsRequest()
{ }
public sealed class Broker
{
public static PermissionsRequest CreatePermissionsRequest()
{
return new PermissionsRequest();
}
public PermissionsRequest CreatePermissionsRequest_Instance()
{
return new PermissionsRequest();
}
}
}
public class UserClass
{
public void Blah()
{
var permissionsRequest = PermissionsRequest.Broker.CreatePermissionsRequest();
var broker = new PermissionsRequest.Broker();
var permRequest = broker.CreatePermissionsRequest_Instance();
}
}

C# static interface or abstract implementation

I have a program that needs to be able to interface with multiple platforms ie read/write files, read/write database or read/write web requests. The platform interface is selected from configuration and does not change while the application is running. I have a single read/write interface class which is inherited by the platform specific classes so that this is abstracted from the rest of the program.
My problem is that I have 10 classes in my framework that will need to use this interface. Instead of making multiple instances of this class, or passing a single reference to every class, I figured it would make sense to make the interface static. Unfortunately I have just learned that Interfaces cannot have static methods, static methods cannot call non-static methods and static methods cannot be abstract.
Can anyone show me another method of approaching this situation?
Edit:
Thanks for everyone's input, here is my solution based on the example given by Patrick Hofman (thank you!)
interface TheInterface
{
void read();
void write();
}
public class X : TheInterface
{
public void read() { //do something }
public void write() { //do something }
}
public class Y : TheInterface
{
public void read() { //do something }
public void write() { //do something }
}
public class FileAccessor
{
public static TheInterface accessor;
public static TheInterface Accessor
{
get
{
if(accessor) return accessor;
}
}
}
This can be called by any class as:
static void Main(string[] args)
{
switch (Config.interface)
{
case "X":
FileAccessor.accessor = new Lazy<X>();
case "Y":
FileAccessor.accessor = new Lazy<Y>();
default:
throw new Lazy<Exception>("Unknown interface: " + Config.interface);
}
FileAccessor.Accessor.read();
}
Indeed, interfaces, or abstract classes can't be static themselves, but the further implementation can. Also, you can use the singleton pattern to make your life easier, and allow inheritance, etc.
public class X : ISomeInterface
{
private X() { }
public static X instance;
public static X Instance
{
get
{
return instance ?? (instance = new X());
}
}
}
Or, using Lazy<T>:
public class X : ISomeInterface
{
private X() { }
public static Lazy<X> instanceLazy = new Lazy<X>(() => new X());
public static X Instance
{
get
{
return instance.Value;
}
}
}
Disclaimer: I am the author of the library described below.
I don't know if this helps you, but I have written a library (very early version yet) that allows you to define static interfaces, by defining normal interfaces and decorating their methods with an attribute named [Static], for example:
public interface IYourInterface
{
[Static]
void DoTheThing();
}
(Note that you don't explicitly add this interface to your implementations.)
Once you have defined the interface, you can instantiate it from within your code with any valid implementation you choose:
return typeof(YourImplementation).ToStaticContract<IYourInterface>();
If the methods can't be found in YourImplementation, this call fails at runtime with an exception.
If the methods are found and this call is successful, then the client code can polymorphically call your static methods like this:
IYourInterface proxy = GetAnImplementation();
proxy.DoTheThing();
You can make a Static Class which has Variable of your Interface.
public static class StaticClass
{
public static ISomeInterface Interface;
}
Now you can access the Instance from everywhere in your Framwork
static void Main(string[] args)
{
StaticClass.Interface = new SomeClass();
}

How to make Singleton a Lazy instantiated class?

I have a class which is lazy instantiated by another library. I don't have control over that library code but still need to be sure it cannot create more than one instance of my class.
Is it possible ? how ?
Some simple solutions to this question hides some problems, for a full understanding of this matter I recommend the reading of the following article
http://www.yoda.arachsys.com/csharp/singleton.html
Which concludes with an optimal solution
public sealed class Singleton
{
Singleton()
{
}
public static Singleton Instance
{
get
{
return Nested.instance;
}
}
class Nested
{
// Explicit static constructor to tell C# compiler
// not to mark type as beforefieldinit
static Nested()
{
}
internal static readonly Singleton instance = new Singleton();
}
}
If it's calling your class's constructor, the only thing you can do is throw an exception in the constructor if you determine that an instance was previously created. Since you don't have control over the other library, you wouldn't be able to use a factory method or static property which would normally be the way you control access to a singleton.
Depending on your situation, you may also look into using a lightweight proxy that wraps a singleton instance. In this example, any number of MyObjectProxy can be created but they all defer their implementation to a single instance of MyObject.
public class MyObject {
internal MyObject() {
}
private int _counter;
public int Increment() {
return Interlocked.Increment(ref _counter);
}
}
public class MyObjectProxy {
private static readonly MyObject _singleton = new MyObject();
public MyObjectProxy() {
}
public int Increment() {
return _singleton.Increment();
}
}

Singleton Pattern for C# [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 4 years ago.
Improve this question
I need to store a bunch of variables that need to be accessed globally and I'm wondering if a singleton pattern would be applicable. From the examples I've seen, a singleton pattern is just a static class that can't be inherited. But the examples I've seen are overly complex for my needs. What would be the very simplest singleton class? Couldn't I just make a static, sealed class with some variables inside?
Typically a singleton isn't a static class - a singleton will give you a single instance of a class.
I don't know what examples you've seen, but usually the singleton pattern can be really simple in C#:
public sealed class Singleton
{
private static readonly Singleton instance = new Singleton();
static Singleton() {} // Make sure it's truly lazy
private Singleton() {} // Prevent instantiation outside
public static Singleton Instance { get { return instance; } }
}
That's not difficult.
The advantage of a singleton over static members is that the class can implement interfaces etc. Sometimes that's useful - but other times, static members would indeed do just as well. Additionally, it's usually easier to move from a singleton to a non-singleton later, e.g. passing in the singleton as a "configuration" object to dependency classes, rather than those dependency classes making direct static calls.
Personally I'd try to avoid using singletons where possible - they make testing harder, apart from anything else. They can occasionally be useful though.
There are several Patterns which might be appropriate for you, a singleton is one of the worse.
Registry
struct Data {
public String ProgramName;
public String Parameters;
}
class FooRegistry {
private static Dictionary<String, Data> registry = new Dictionary<String, Data>();
public static void Register(String key, Data data) {
FooRegistry.registry[key] = data;
}
public static void Get(String key) {
// Omitted: Check if key exists
return FooRegistry.registry[key];
}
}
Advantages
Easy to switch to a Mock Object for automated testing
You can still store multiple instances but if necessary you have only one instance.
Disadvantages
Slightly slower than a Singleton or a global Variable
Static Class
class GlobalStuff {
public static String ProgramName {get;set;}
public static String Parameters {get;set;}
private GlobalStuff() {}
}
Advantages
Simple
Fast
Disadvantages
Hard to switch dynamically to i.e. a Mock Object
Hard to switch to another object type if requirements change
Simple Singleton
class DataSingleton {
private static DataSingleton instance = null;
private DataSingleton() {}
public static DataSingleton Instance {
get {
if (DataSingleton.instance == null) DataSingleton.instance = new DataSingleton();
return DataSingleton;
}
}
}
Advantages
None really
Disadvantages
Hard to create a threadsafe singleton, the above Version will fail if multiple threads access the instance.
Hard to switch for a mock object
Personally I like the Registry Pattern but YMMV.
You should take a look at Dependency Injection as it's usually considered the best practice but it's too big a topic to explain here:
Dependency Injection
A Singleton isn't just a static class that can't be inherited. It's a regular class that can be instantiated only once, with everybody sharing that single instance (and making it thread safe is even more work).
The typical .NET code for a Singleton looks something like the following. This is a quick example, and not by any means the best implementation or thread-safe code:
public sealed class Singleton
{
Singleton _instance = null;
public Singleton Instance
{
get
{
if(_instance == null)
_instance = new Singleton();
return _instance;
}
}
// Default private constructor so only we can instanctiate
private Singleton() { }
// Default private static constructor
private static Singleton() { }
}
If you're going to go down the path you're thinking, a static sealed class will work just fine.
Using C# 6 Auto-Property Initializers.
public sealed class Singleton
{
private Singleton() { }
public static Singleton Instance { get; } = new Singleton();
}
Short and clean - I'll be happy to hear the downsides.
I know this Issue is old, but here is another solution using .Net 4.0 or later (including .Net Core and .Net Standard).
First, define your class that will be transformed into a Singleton:
public class ClassThatWillBeASingleton
{
private ClassThatWillBeASingleton()
{
Thread.Sleep(20);
guid = Guid.NewGuid();
Thread.Sleep(20);
}
public Guid guid { get; set; }
}
In this Example Class I've defined one constructor that Sleeps for a while, and then creates one new Guid and save to it's public property. (The Sleep is just for concurrency testing)
Notice that the constructor is private, so that no one can create a new instance of this class.
Now, We need to define the wrapper that will transform this class into a singleton:
public abstract class SingletonBase<T> where T : class
{
private static readonly Lazy<T> _Lazy = new Lazy<T>(() =>
{
// Get non-public constructors for T.
var ctors = typeof(T).GetConstructors(System.Reflection.BindingFlags.Instance |
System.Reflection.BindingFlags.NonPublic);
if (!Array.Exists(ctors, (ci) => ci.GetParameters().Length == 0))
throw new InvalidOperationException("Non-public ctor() was not found.");
var ctor = Array.Find(ctors, (ci) => ci.GetParameters().Length == 0);
// Invoke constructor and return resulting object.
return ctor.Invoke(new object[] { }) as T;
}, System.Threading.LazyThreadSafetyMode.ExecutionAndPublication);
public static T Instance
{
get { return _Lazy.Value; }
}
}
Notice that it uses Lazy to create a field _Lazy that knows how to instantiate a class using it's private constructor.
And it defines one Property Instance to access the Value of the Lazy field.
Notice the LazyThreadSafetyMode enum that is passed to the Lazy constructor. It is using ExecutionAndPublication. So only one thread will be allowed to initialize the Value of the Lazy field.
Now, all we have to do is define the wrapped class that will be a singleton:
public class ExampleSingleton : SingletonBase<ClassThatWillBeASingleton>
{
private ExampleSingleton () { }
}
Here is one example of the usage:
ExampleSingleton.Instance.guid;
And one test to assert that two threads will get the same instance of the Singleton:
[Fact()]
public void Instance_ParallelGuid_ExpectedReturnSameGuid()
{
Guid firstGuid = Guid.Empty;
Guid secondGuid = Guid.NewGuid();
Parallel.Invoke(() =>
{
firstGuid = Singleton4Tests.Instance.guid;
}, () =>
{
secondGuid = Singleton4Tests.Instance.guid;
});
Assert.Equal(firstGuid, secondGuid);
}
This test is calling the Value of the Lazy field concurrently, and we want to assert that both instances that will be returned from this property (Value of Lazy) are the same.
More details about this subject can be found at: C# in Depth
So, as far as I am concerned, this is the most concise and simple implementation of the Singleton pattern in C#.
http://blueonionsoftware.com/blog.aspx?p=c6e72c38-2839-4696-990a-3fbf9b2b0ba4
I would, however, suggest that singletons are really ugly patterns... I consider them to be an anti-pattern.
http://blogs.msdn.com/scottdensmore/archive/2004/05/25/140827.aspx
For me, I prefer to have something like a Repository, implementing IRepository. Your class can declare the dependency to IRepository in the constructor and it can be passed in using Dependency Injection or one of these methods:
http://houseofbilz.com/archive/2009/05/02.aspx
Use your language features.
Mostly simple thread-safe implementation is:
public sealed class Singleton
{
private static readonly Singleton _instance;
private Singleton() { }
static Singleton()
{
_instance = new Singleton();
}
public static Singleton Instance
{
get { return _instance; }
}
}
...what would be the very simplest singleton class?
Just to add one more possible solution. The simplest, most straight forward and easy to use approach I can think of would be something like this:
//The abstract singleton
public abstract class Singleton<T> where T : class
{
private static readonly Lazy<T> instance = new Lazy<T>( CreateInstance, true );
public static T Instance => instance.Value;
private static T CreateInstance()
{
return (T)Activator.CreateInstance( typeof(T), true);
}
}
//This is the usage for any class, that should be a singleton
public class MyClass : Singleton<MyClass>
{
private MyClass()
{
//Code...
}
//Code...
}
//Example usage of the Singleton
class Program
{
static void Main(string[] args)
{
MyClass clazz = MyClass.Instance;
}
}

Categories