Create a private static member variable of your class of the same type as your class and call it singleInstance or similar.
Create a static initialiser which is like a normal constructor but with the keyword static in front of it. In this method create a new instance of the class and assign it to the singleInstance member variable.
Modify your constructor so that it is private. This ensures that no one else can create your class.
Create a new static public get property called Instance or similar and return the singleInstance member variable.
The remainder of the class is as you would normally have it.
You have now created a singleton. Every time you want to use the class you access it through the Instance property. This version of a singleton will be created at application start up.
If you want to delay the initialisation until first use then you can remove the static initialiser and have the code for the Instance property check singleInstance == null in which case a new instance of the class is created and assigned to singleInstance first. Then it returns singleInstance as it did before.
desmond5 wrote: Where could I find more info on static initializers ?
Sorry, my fault - I was using Java terminology. In C# they are actually called static constructors. See this MSDN document[^]
[Edit]Ooops! I fixed some bugs[/Edit]
// This is the static member variable that will hold// the one and only instance of this class.privatestatic MySingletonClass onlyInstance;
// This is the static constructorstatic MySingletonClass()
// Do initialisation of static member variables.
onlyInstance = new MySingletonClass();
// This is the instance constructorpublic MySingletonClass()
// Do initialisation of instance member variables
// Allows access to the only instance of the classpublic MySingletonClass Instance
desmond5 wrote: singletons has something to do with thread-safety
I don't see why it cannot be used in a thead safety mechanism. However I've never used a singleton for that purpose.
For instance if you have a singleton that controls access to a shared resource then in each of you instance methods and properties (not the static ones) you can lock(this) to ensure that not other thread has access to your singleton while some sensitive operation is being carried out. See MSDN[^] for more information.
// This is the static member variable that will hold// the one and only instance of this class.publicstaticreadonly MySingletonClass Instance = new MySingletonClass();
// Make the instance constructor private to make sure that there will be// only one instance of this class.private MySingletonClass()
// Do initialisation of instance member variables
// Skip the static constructor and the static property
Arjan Einbu wrote: The readonly keyword makes it work exactly the same way as the property getter.
If all you do in the property getter is return the member variable (field) then there isn't much difference.
As an absolute rule I never ever under any circumstances reveal the member variables of a class as public. Readonly or not. It breaks the OO rule on encapsulation.
What if you change the design of the class later on? You've publicly exposed the inner workings of the class! Using properties you can hide the inner workings, you can implement lazy lookup (my second suggestion employed a form of lazy lookup - the singleton is not created until needed), the innards of the class can change and the code for the property can coerce the expected value out so that existing code doesn't notice the difference.
Colin Angus Mackay wrote: If all you do in the property getter is return the member variable (field) then there isn't much difference.
You did in your example... ;)
I know the rules of OO, but i believe rules can be broken sometimes if it serves a greater purpose. (Less code, fewer sources of error, greater maintainability.)
You're absolutely right that you might want to change your code later on, and if other assemblies access my field, they will need to be recompiled if that field later on is changed to a property. So if some other assemblies are going to use that singleton, one should consider wrapping it up in a property, as you say, Colin.
(Also, public fields cannot be made part of an interface definition, so there can be several reasons to make it a property.)
However, if the field is accessed only from within the same assembly (or assemblies that are compiled together with the containing assembly) it will make no difference if you change the field to a property. This is very often the case. (Though one should perhaps mark the property as internal instead of public in that case.)
Encapsulation is preserved i this construct. By making the instance constructor private, we make sure there will be made no other instances of the singleton. Revealing the inner workings on this construct wont do any harm. The knowledge gained from it can't be abused to access inner data in other ways than the way we planned for.
Arjan Einbu wrote: I know the rules of OO, but i believe rules can be broken sometimes if it serves a greater purpose. (Less code, fewer sources of error, greater maintainability.)
Many years ago I worked with a programmer that would take this statement and abuse it to the extent that everything would be public! He'd interpret it as: Less code == fewer sources of error == greater maintainability
You make a very good argument in this case for allowing the public readonly field. However by the time I thought through all the possible senarios for each member variable I create and decide whether to fully encapsulate it or decide that it is safe to expose I could have written a default compliment of getters/setters for them.
By the way, is there a way to "shorten the patch" to the singleton ? I mean, I have to write right now MainMameSpace.MyClasses.PropertiesClass.Instance.SomeFunction, but it would be much easier if it could be just MainNameSpace.PropertiesInstancel.SomeFunction.
Isn't it possible to access the ProperitesClass.Instance through a pointer or something ?
At the top of the file you can add using statements so that you can short circuit the path to the classes. If there is any ambiguity, for example two classes with the same name but in different namespaces, you will still have to use the full path.
then later in your code you can just put:
C# only permits pointers in unsafemethods. However if you are going to use the instance a lot then you can just assign it to a variable as normal. e.g.
hi, im using a datagrid generated from a XML file using the VS XSD builder. now i want to add a "virtual" colum that add's some extra information, i only need this information on the runtime so i don't wanna add it to the XML file.
i have read some examples with "BindingContext" and "Expression" but this examples are mostly DataGridBoolColumn and no TextColums.
dose anybody knows a tuturial or have some example code?
First, you should consider using DataGridTableStyle(s) to control exactly what the user sees (for instance, if you have a PK in your strongly-typed DataSet as a numeric type, users probably don't need to see that). This will allow you to add columns that aren't bound to the DataSet as well.
i am try to do like this ....
i have a win form textbox and i am trying to write something like "jacal99" using threading with five seconds interval .... the value of thread was thread.sleep(5000);
but when the next charactor try to print in the textbox the first value gone.
i want to pring "jacal99" with five seconds interval .... every charactor...
Hi again. Still learning C#. This time I managed to create 2 similar controls. I also have a class PropertiesClass that should change some properties (like color and text) of the controls. But after I have changed a property in PropertiesClass, how can I let the other (two) controls know that I did it ? I remind You that I have several controls that must be updated, not just one. I guess the only chance would be using events somehow ?
From my Borland Delphi days I remember using messages (if property is changed I broadcast the message and the controls respond to it) for things like this, but unfortunately (or luckily) .NET doesn't support them...
I'm very new to C# and I have some questions about writing my own controls (I thought I can learn it best that way). I have two classes - one containing a procedure that paints a area (draws a custom 3D border and background) and another class is a control, witch must call the painting method (that is in the first class) in OnPaint method.
What I don't understand here is how can I pass the area of control as a parameter of the method?
Like in Borland Delphi I would have done it like this:
procedure PaintControl(AreaToPaint: Rect)
Or with two points (one x1, y1 and another x2,x2).
How can I do this in C# ?
If you understood even a little what I'm talking about, please reply....