Related
What I am currently atempting to make is an inventory system. I wonder if I can store the current method and then open the inventory, and when I am done there, reopen/recall the previus method that ran.
You haven't provided very much information but I can tell you don't want to store a method, you want to store an object.
An object is an instance of a class. Depending on the kind of class you have you can either create multiple instances of a class and instantiate them multiple times across your application. Or alternatively you can create single instances of an object that you use throughout your entire application/game.
From the sounds of it, you want to use a singleton class that retains the current values of the user's inventory. So if you interact with the inventory class in one part of your program, you would like to then view and interact with the same previously modified values stored within the singleton from another part of your program.
I can't give you a concrete answer to your problem, but a possible Singleton class for your use case would look something like this;
public sealed class Inventory
{
private static readonly Inventoryinstance = new Inventory();
// Explicit static constructor to tell C# compiler
// not to mark type as before field init
static Inventory()
{
}
private Inventory()
{
// optionally, pre-populate with data stored in database when constructed
}
public static Inventory Instance
{
get
{
return instance;
}
}
public List<InventoryItem> InventoryItems { get; set; } = new List<InventoryItem>();
public void AddItemToInventory(InventoryItem item) {
InventoryItems.Add(item);
}
public void RemoveItemFromInventory(InventoryItem item) {
InventoryItems.Remove(item);
}
}
You can use this site for reference - https://csharpindepth.com/articles/singleton
If you have an application that utilises DI, you can create singleton instances that are injectable into your other app classes. This is a better way of handling singletons as they are handled by an IoC system rather than being made static for the entire application to access.
I want two share a DepedencyProperty between to classes using AddOwner (any other approach is welcome), e.g.
class ClassA : DependencyObject
{
public int Number
{
get { return (int)GetValue(NumberProperty); }
set { SetValue(NumberProperty, value); }
}
public static readonly DependencyProperty NumberProperty =
DependencyProperty.Register("Number", typeof(int), typeof(ClassA),
new FrameworkPropertyMetadata(0,
FrameworkPropertyMetadataOptions.Inherits));
}
and
class ClassB : DependencyObject
{
public int Number
{
get { return (int)GetValue(NumberProperty); }
set { SetValue(NumberProperty, value); }
}
public static readonly DependencyProperty NumberProperty =
ClassA.NumberProperty.AddOwner(typeof(ClassB),
new FrameworkPropertyMetadata(0,
FrameworkPropertyMetadataOptions.Inherits));
}
like described here. As you might guess: Of course it doesn't work. That makes perfect sense, because it would make it impossible to create multiple instances of the same class that all have their "own" dependency property.
How do I make sure that all classes (and especially all instances) of ClassA, ClassB and any other class which refers to the property are talking about the exact same property (and therefore value)? A Singleton is no option, since Class A is a MainWindow and Class B is an UserControl (protected constructors are therefore not possible).
Regards,
Ben
I think you're misunderstanding the purpose of DependencyProperties.
They are basically a Property Definition, without a property Value.
They define things like name, type, default value, location of the value, etc however they do not contain the actual value itself. This allows the value to be provided with a binding pointing to any other property in any other location.
Your best bet is to probably just create a property that is backed by a singleton property.
public int Number
{
get { return MySingleton.Number; }
set { MySingleton.Number = value; }
}
Edit
Based on comments below where you say you want all instances of the object to respond to change notifications from any of the other objects, you'd want to implement INotifyPropertyChanged on your singleton object, and subscribe to it's PropertyChange event in each class that uses that value.
For example,
public ClassA
{
public ClassA()
{
MySingleton.PropertyChanged += Singleton_PropertyChanged;
}
void Singleton_PropertyChanged(object sender, NotifyPropertyChangedEventArgs e)
{
// if singleton's Number property changed, raise change
// notification for this class's Number property too
if (e.PropertyName == "Number")
OnPropertyChanged("Number");
}
public int Number
{
get { return MySingleton.Number; }
set { MySingleton.Number = value; }
}
}
One possible solution to what you want here is to use another class where you store that
value. e.g.
public class SomeValueStore : IValueStore
{
int myValue {get; set;}
}
Then, whereever you need that value, you can use Dependency injection to get it.
somewhere at Bootstrapper:
RootContainer.Register<IValueStore>(new SomeValueStore);
and in code:
var valueStore = RootContainer.Resolve<IValueStore();
valueStore.myValue = 42;
This is just an idea (And I know we have a ServiceLocator here).
Perhaps you can store a reference to that ValueStore somewhere where you
can get it from both classes you need it as a simple solution.
public SomeClassYouHaveAccessToFromBothSides
{
public IValueStore _store = new SomeValueStore();
}
Please excuse me. I do not have access to my repo / visual studio right now
so I cannot give better example. But I think the underlying idea is clear.
I created a class which allows access to global access to a variable while only creating it once, essentially a singleton.
However, it doesn't match any of the 'correct' ways to implement a singleton. I assume that it's not mentioned because there is something 'wrong' with it but I can't see any problem with it other then the lack of lazy initialization.
Any thoughts?
static class DefaultFields
{
private static readonly string IniPath = Path.Combine(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location), "defaultFields.ini");
private static readonly IniConfigSource Ini = GetIni();
/// <summary>
/// Creates a reference to the ini file on startup
/// </summary>
private static IniConfigSource GetIni()
{
// Create Ini File if it does not exist
if (!File.Exists(IniPath))
{
using (FileStream stream = new FileStream(IniPath, FileMode.CreateNew))
{
var iniConfig = new IniConfigSource(stream);
iniConfig.AddConfig("default");
iniConfig.Save(IniPath);
}
}
var source = new IniConfigSource(IniPath);
return source;
}
public static IConfig Get()
{
return Ini.Configs["default"];
}
public static void Remove(string key)
{
Get().Remove(key);
Ini.Save();
}
public static void Set(string key, string value)
{
Get().Set(key, value ?? "");
Ini.Save();
}
}
It doesn't follow the usual singleton patterns as your class is static and just controls access to static variables.
Where as a singleton is normally a static single instance of a class where the only static functions are that to create and access the singleton that stores variables as normal non static member variables.
Meaning the class could quite easily be changed or made to be instanced more then once but yours cannot
You are right about the singleton, its a class with a unique instance that provides global access.
It might seem like a static class but usually its implemented in a different way.
Also bear in mind that this pattern should be used with some precaution, as its really hard to refactor out a singleton once its deep in the code. Should be used primarily when you have hardware constraints or are implemented unique points of access to a factory. I would try to avoid it whenever possible.
An example of an implementation is as follows:
public class A
{
/// <summary>
/// Unique instance to access to object A
/// </summary>
public static readonly A Singleton = new A();
/// <summary>
/// private constructor so it can only be created internally.
/// </summary>
private A()
{
}
/// <summary>
/// Instance method B does B..
/// </summary>
public void B()
{
}
}
And could be used like
A.Singleton.B()
Hope that helps.
All the methods on your class are static, so you are hiding the single instance from your users. With the singleton pattern the single instance is exposed via a public property usually called Instance (in other languages like Java it might be a method called getInstance or similar).
Your code is not wrong - it's just not the singleton pattern. If you wish to implement a singleton I would recommend Jon Skeet's article Implementing the Singleton Pattern in C#.
The biggest problem I see is that you're not doing any SyncLock-ing around writes to your INI file - multiple threads that attempt to write values at the same time could end up with unpredictable results, like both making writes and only one persisting (or multiple threads attempting to write the file at once, resulting in an IO error).
I'd create a private "Locking" object of some kind and then wrap the writes to your file in a SyncLock to ensure that only one thread at a time has the ability to change values (or, at the very least, commit changes to the INI file).
I am interested in answers to this question as well. In my opinion, there is a flood of singleton examples that use lazy instantiation, but I think you have to ask yourself if it's really necessary on a case by case basis.
Although this article pertains to Java, the concepts should still apply. This provides a number of examples for different singleton implementations. http://www.shaunabram.com/singleton-implementations/
I've also seen numerous references to the book "Effective Java", Item 71 - use lazy instantiation judiciously. Basically, don't do it unless you need to.
That's not really a singleton, it's a static class.
In many ways, static classes are similar to singleton's, true. But static classes can't implement interfaces, can't inherit functionality from a base class, and you can't carry a reference to them.
Why the readonly on the Ini field?
But if you want implement the singleton pattern, it's something like this:
static DefaultFields
{
private readonly string IniPath = Path.Combine(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location), "defaultFields.ini");
private readonly IniConfigSource Ini = GetIni();
private static DefaultFields _default;
public static DefaultFields Default
{
get { if(this._default == null){ this._default = new DefaultFields(); } return this._default; }
}
private DefaultFields()
{
}
/// <summary>
/// Creates a reference to the ini file on startup
/// </summary>
private IniConfigSource GetIni()
{
// Create Ini File if it does not exist
if (!File.Exists(IniPath))
{
using (FileStream stream = new FileStream(IniPath, FileMode.CreateNew))
{
var iniConfig = new IniConfigSource(stream);
iniConfig.AddConfig("default");
iniConfig.Save(IniPath);
}
}
var source = new IniConfigSource(IniPath);
return source;
}
public IConfig Get()
{
return Ini.Configs["default"];
}
public void Remove(string key)
{
Get().Remove(key);
Ini.Save();
}
public void Set(string key, string value)
{
Get().Set(key, value ?? "");
Ini.Save();
}
}
lazy initialization is very important for a singleton class. By declaring your class to be static you implement a static class, not a singleton class.
How do I implement the singleton pattern in C#? I want to put my constants and some basic functions in it as I use those everywhere in my project. I want to have them 'Global' and not need to manually bind them every object I create.
If you are just storing some global values and have some methods that don't need state, you don't need singleton. Just make the class and its properties/methods static.
public static class GlobalSomething
{
public static int NumberOfSomething { get; set; }
public static string MangleString( string someValue )
{
}
}
Singleton is most useful when you have a normal class with state, but you only want one of them. The links that others have provided should be useful in exploring the Singleton pattern.
Singletons only make sense if both of these conditions are true:
The object must be global
There must only ever exist a single instance of the object
Note that #2 does not mean that you'd like the object to only have a single instance - if thats the case, simply instantiate it only once - it means that there must (as in, it's dangerous for this not to be true) only ever be a single instance.
If you want global, just make a global instance of some (non signleton) object (or make it static or whatever).
If you want only one instance, again, static is your friend. Also, simply instantiate only one object.
Thats my opinion anyway.
Singleton != Global. You seem to be looking for the keyword static.
You can really simplify a singleton implementation, this is what I use:
internal FooService() { }
static FooService() { }
private static readonly FooService _instance = new FooService();
public static FooService Instance
{
get { return _instance; }
}
Hmm, this all seems a bit complex.
Why do you need a dependency injection framework to get a singleton? Using an IOC container is fine for some enterprise app (as long as it's not overused, of course), but, ah, the fella just wants to know about implementing the pattern.
Why not always eagerly instantiate, then provide a method that returns the static, most of the code written above then goes away. Follow the old C2 adage - DoTheSimplestThingThatCouldPossiblyWork...
I would recommend you read the article Exploring the Singleton Design Pattern available on MSDN. It details the features of the framework which make the pattern simple to implement.
As an aside, I'd check out the related reading on SO regarding Singletons.
Ignoring the issue of whether or not you should be using the Singleton pattern, which has been discussed elsewhere, I would implement a singleton like this:
/// <summary>
/// Thread-safe singleton implementation
/// </summary>
public sealed class MySingleton {
private static volatile MySingleton instance = null;
private static object syncRoot = new object();
/// <summary>
/// The instance of the singleton
/// safe for multithreading
/// </summary>
public static MySingleton Instance {
get {
// only create a new instance if one doesn't already exist.
if (instance == null) {
// use this lock to ensure that only one thread can access
// this block of code at once.
lock (syncRoot) {
if (instance == null) {
instance = new MySingleton();
}
}
}
// return instance where it was just created or already existed.
return instance;
}
}
/// <summary>
/// This constructor must be kept private
/// only access the singleton through the static Instance property
/// </summary>
private MySingleton() {
}
}
Static singleton is pretty much an anti pattern if you want a loosely coupled design. Avoid if possible, and unless this is a very simple system I would recommend having a look at one of the many dependency injection frameworks available, such as http://ninject.org/ or http://code.google.com/p/autofac/.
To register / consume a type configured as a singleton in autofac you would do something like the following:
var builder = new ContainerBuilder()
builder.Register(typeof(Dependency)).SingletonScoped()
builder.Register(c => new RequiresDependency(c.Resolve<Dependency>()))
var container = builder.Build();
var configured = container.Resolve<RequiresDependency>();
The accepted answer is a terrible solution by the way, at least check the chaps who actually implemented the pattern.
public class Globals
{
private string setting1;
private string setting2;
#region Singleton Pattern Implementation
private class SingletonCreator
{
internal static readonly Globals uniqueInstance = new Globals();
static SingletonCreator()
{
}
}
/// <summary>Private Constructor for Singleton Pattern Implementaion</summary>
/// <remarks>can be used for initializing member variables</remarks>
private Globals()
{
}
/// <summary>Returns a reference to the unique instance of Globals class</summary>
/// <remarks>used for getting a reference of Globals class</remarks>
public static Globals GetInstance
{
get { return SingletonCreator.uniqueInstance; }
}
#endregion
public string Setting1
{
get { return this.setting1; }
set { this.setting1 = value; }
}
public string Setting2
{
get { return this.setting2; }
set { this.setting2 = value; }
}
public static int Constant1
{
get { reutrn 100; }
}
public static int Constat2
{
get { return 200; }
}
public static DateTime SqlMinDate
{
get { return new DateTime(1900, 1, 1, 0, 0, 0); }
}
}
I like this pattern, although it doesn't prevent someone from creating a non-singleton instance. It can sometimes can be better to educate the developers in your team on using the right methodology vs. going to heroic lengths to prevent some knucklehead from using your code the wrong way...
public class GenericSingleton<T> where T : new()
{
private static T ms_StaticInstance = new T();
public T Build()
{
return ms_StaticInstance;
}
}
...
GenericSingleton<SimpleType> builder1 = new GenericSingleton<SimpleType>();
SimpleType simple = builder1.Build();
This will give you a single instance (instantiated the right way) and will effectively be lazy, because the static constructor doesn't get called until Build() is called.
What you are describing is merely static functions and constants, not a singleton. The singleton design pattern (which is very rarely needed) describes a class that is instantiated, but only once, automatically, when first used.
It combines lazy initialization with a check to prevent multiple instantiation. It's only really useful for classes that wrap some concept that is physically singular, such as a wrapper around a hardware device.
Static constants and functions are just that: code that doesn't need an instance at all.
Ask yourself this: "Will this class break if there is more than one instance of it?" If the answer is no, you don't need a singleton.
hmmm... Few constants with related functions... would that not better be achieved through enums ? I know you can create a custom enum in Java with methods and all, the same should be attainable in C#, if not directly supported then can be done with simple class singleton with private constructor.
If your constants are semantically related you should considered enums (or equivalent concept) you will gain all advantages of the const static variables + you will be able to use to your advantage the type checking of the compiler.
My 2 cent
Personally I would go for a dependency injection framework, like Unity, all of them are able to configure singleton items in the container and would improve coupling by moving from a class dependency to interface dependency.
You can make a simple manual static singleton implementation for your common (non-static) class by adding a static property Instance (name can vary) into it with initialization like this:
public class MyClass
{
private static MyClass _instance;
public static MyClass Instance => _instance ?? (_instance = new MyClass());
// add here whatever constructor and other logic you like or need.
}
Then it can be resolved anywhere from this namespace like this:
var myClass = MyClass.Instance; // without any new keyword
myClass.SomeNonStaticMethod();
// or:
MyClass.Instance.SomeNonStaticMethod();
// or:
MyClass.Instance.SomeNonStaticProperty = "new value";
By hiding public constructor, adding a private static field to hold this only instance, and adding a static factory method (with lazy initializer) to return that single instance
public class MySingleton
{
private static MySingleton sngltn;
private static object locker;
private MySingleton() {} // Hides parameterless ctor, inhibits use of new()
public static MySingleton GetMySingleton()
{
lock(locker)
return sngltn?? new MySingleton();
}
}
I have written a class for my project using Singleton pattern. It is very easy to use. Hope it will work for you. Please find the code following.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace TEClaim.Models
{
public class LogedinUserDetails
{
public string UserID { get; set; }
public string UserRole { get; set; }
public string UserSupervisor { get; set; }
public LogedinUserDetails()
{
}
public static LogedinUserDetails Singleton()
{
LogedinUserDetails oSingleton;
if (null == System.Web.HttpContext.Current.Session["LogedinUserDetails"])
{
oSingleton = new LogedinUserDetails();
System.Web.HttpContext.Current.Session["LogedinUserDetails"] = oSingleton;
}
else
{
oSingleton = (LogedinUserDetails)System.Web.HttpContext.Current.Session["LogedinUserDetails"];
}
//Return the single instance of this class that was stored in the session
return oSingleton;
}
}
}
Now you can set variable value for the above code in your application like this..
[HttpPost]
public ActionResult Login(FormCollection collection)
{
LogedinUserDetails User_Details = LogedinUserDetails.Singleton();
User_Details.UserID = "12";
User_Details.UserRole = "SuperAdmin";
User_Details.UserSupervisor = "815978";
return RedirectToAction("Dashboard", "Home");
}
And you can retrieve those value like this..
public ActionResult Dashboard()
{
LogedinUserDetails User_Details = LogedinUserDetails.Singleton();
ViewData["UserID"] = User_Details.UserID;
ViewData["UserRole"] = User_Details.UserRole;
ViewData["UserSupervisor"] = User_Details.UserSupervisor;
return View();
}
In c# it could be (Thread safe as well as lazy initialization):
public sealed class MySingleton
{
static volatile Lazy<MySingleton> _instance = new Lazy<MySingleton>(() => new MySingleton(), true);
public static MySingleton Instance => _instance.Value;
private MySingleton() { }
}
All I need is a way to make a property of one class only 'settable' from one other class (a sort of manager class).
Is this even possible in c#?
My colleague 'reliably' informs me that I have a design flaw, but I feel I should at least ask the community before I concede defeat!
No, it's not really possible to do this in any clean way in C#. You probably have a design flaw ;-)
You can use the internal modifier, which lets all types in the same assembly access the data (or nominated assemblies if using [InternalsVisibleTo] - but no: there is no friend equivalent in C#.
For example:
public string Foo {get; internal set;}
You have a design flaw. Also, don't be paranoid about data hiding. Here's 3.5's way to do it:
class Program
{
static void Main(string[] args)
{
Managed m = new Managed();
Console.WriteLine(m.PrivateSetter);
m.Mgr.SetProperty("lol");
Console.WriteLine(m.PrivateSetter);
Console.Read();
}
}
public class Managed
{
private Manager _mgr;
public Manager Mgr
{
get { return _mgr ?? (_mgr = new Manager(s => PrivateSetter = s)); }
}
public string PrivateSetter { get; private set; }
public Managed()
{
PrivateSetter = "Unset";
}
}
public class Manager
{
private Action<string> _setPrivateProperty;
public Manager(Action<string> setter)
{
_setPrivateProperty = setter;
}
public void SetProperty(string value)
{
_setPrivateProperty(value);
}
}
Here's how we'd do it in pre-lambda days:
public class Managed
{
private Manager _mgr;
public Manager Mgr
{
get { return _mgr ?? (_mgr = new Manager(this)); }
}
public string PrivateSetter { get; private set; }
public Managed()
{
PrivateSetter = "Unset";
}
public class Manager
{
public void SetProperty(string value)
{
m.PrivateSetter = value;
}
private Managed m;
public Manager(Managed man)
{
m = man;
}
}
}
The best way to do it would be:
/// <summary>
/// Gets or sets foo
/// <b>Setter should only be invoked by SomeClass</b>
/// </summary>
public Object Foo
{
get { return foo; }
set { foo = value; }
}
When you have some complex access or inheritance restriction, and enforcing it demands too much complexity in the code, sometimes the best way to do it is just properly commenting it.
Note however that you cannot rely on this if this restriction has some security implications, as you are depending on the goodwill of the developer that will use this code.
You cannot do that on that way, but you can access a property's setter method from a derived class, so you can use inheritance for the purpose. All you have to do is to place protected access modifier. If you try to do so, your colleague is right :). You can try doing it like this:
public string Name
{
get{ return _name; }
protected set { _name = value; }
}
keep in mind that the set method of the property is only accessible from the derived class.
Or you could have these two classes in an assembly alone and have the setter as internal. I would vote up for the design flaw though, unless the previous answer by milot (inheriting and protected) makes sense.
You could do:
public void setMyProperty(int value, Object caller)
{
if(caller is MyManagerClass)
{
MyProperty = value;
}
}
This would mean that you could use a 'this' pointer from the calling class. I would question the logic of what you're attempting to achieve, but without knowing the scenario I can't advise any futher. What I will say is this: if it is possible to refactor your code to make it clearer, then it is often worthwhile doing so.
But this is pretty messy and certinly NOT fool-proof ... you have been warned!
Alternativly...
You could pass a delegate from the Class with the Property (Class A) to the Manager Class (Class B). The delegate can refer to a private function within A to allow B to call that delegate as any normal function. This precludes that A knows about B and potentially that A is created before B. Again... messy and not fool-proof!
You can achieve to this by making a Public property in your "settable class" that will inherit from the real class that will have a protected property... this way only the inherit class can SET and not class that doesn't inherit. But the drawback is that you will require to have an inherit class...
Reflection, though I would agree that having to do this just to get around an access modifier is probably an indication of a bad design.
public class Widget
{
private int count;
public int Count
{
get { return this.count; }
private set { this.count = value; }
}
}
public static class WidgetManager
{
public static void CatastrophicErrorResetWidgetCount( Widget widget )
{
Type type = widget.GetType();
PropertyInfo info = type.GetProperty("Count",BindingFlags.Instance|BindingFlags.NonPublic);
info.SetValue(widget,0,null);
}
}
The reason this is a design flaw is because it seems muddled between the scope of the two objects.
The properties of a class should be accessible in the context of that class, at least internally.
It sounds like the settable property on your item class is really a property of the manager class.
You could do something similar to what you want by closely coupling the two classes:
public class MyItem {
internal MyItemManager manager { get;set; }
public string Property1 {
get { return manager.GetPropertyForItem( this ); }
}
}
Unfortunately this isn't great design either.
What your looking for is what C++ calls a Friend class but neither c# or vb has this functionality. There is a lot of debate as to the merit of such functionality since it almost encourages very strong coupling between classes. The only way you could implement this in c# would be with reflection.
If your goal is to have a class Foo let some property (e.g. Bar, of type Biz) to be changed by some other object, without exposing it publicly, a simple way to do that is to have an instance of Foo which is supposed to be changeable by some other object to pass that other object an Action<Biz> which points to a private method that changes Bar to the passed-in value. The other object may use that delegate to change the Bar value of the object that supplied it.
If one wishes to have give all instances of some type Woozle the ability to set the Bar value of any instance of Foo, rather than exposing such abilities on a per-instance basis, one may require that Woozle have a public static method Woozle.InstallFooBarSetter which takes a parameter of type Action<Foo, Biz> and one of type Object. Foo should then have a static method WoozleRequestBarSetter which takes an Object, and passes it to Woozle.InstallFooBarSetter along with an Action<Foo,Biz>. The class initializer for Woozle should generate a new Object, and pass it to Foo.RequestBarSetter; that will pass the object to Woozle.InstallFooBarSetter along with a delegate. Woozle can then confirm that the passed-in object is the one that it generated, and--if so--install the appropriate delegate. Doing things this way will ensure that nobody but Woozle can get the delegate (since the delegate is only passed to Woozle.InstallFooBarSetter), and Woozle can be sure its delegate comes from Foo (since nobody else would have access to the object that Woozle created, and Woozle.InstallFooBarSetter won't do anything without it).
if it is a design flaw depends on what you want to do. You could use the StackTrace class from System.Diagnostics to get the Type of the class setting your property and then compare to the type you want to allow setting yor property..but maybe there are better ways for performing something like this (e.g. boxing)