How should I design something like this? I have a projects that have many classes and I wish to have a counter (int type) that can be accessed by these classes. There should be only one instance of the variable and every time it will add one to the variable.
Use a static class with a public property would be the most simple solution. Depending on your situation, you need more advanced options (for multihreading, unittesting/mocking etc.)
You could use a singleton class to make testing a bit easier and locking in case of multithreading.
An example could be:
public class Counting
{
private readonly Object _thisLock = new Object();
private static readonly Lazy<Counting> InstanceField =
new Lazy<Counting>(() => new Counting());
public static Counting Instance // Singleton
{
get
{
return InstanceField.Value;
}
}
private int _counter;
public int Counter
{
get
{
return _counter;
}
set
{
lock (_thisLock) // Locking
{
_counter = value;
}
}
}
protected Counting()
{
}
}
And use it this way:
Counting.Instance.Counter ++;
You can create a utility static class with all static memebers.
static class Utility
{
public static int Count = 123;//some value
/*some other variables*/
}
class MyClass
{
int mycount = Utility.Count;
}
Note: if you want to access your utility class outside the assembly you need to make your class as public
Related
I have a C# static class accessed from multiple threads. Two questions:
Are my private static fields thread safe when the field is initialized on declaration?
Should I lock when creating private static fields from within static constructor?
Usage of static class from different threads:
class Program
{
static void Main(string[] args)
{
for (int i = 0; i < 100; i++)
{
Task.Run(() =>
{
string name = MyStaticClass.GetValue(9555);
//...
});
}
}
}
Option 1 of static class:
public static class MyStaticClass
{
private static MyClass _myClass = new MyClass();
public static string GetValue(int key)
{
return _myClass.GetValue(key);
}
}
Option 2 of static class:
public static class MyStaticClass
{
private static MyClass _myClass;
private static object _lockObj = new object();
static MyStaticClass()
{
InitMyClass();
}
private static void InitMyClass()
{
if (_myClass == null)
{
lock(_lockObj)
{
if (_myClass == null)
{
_myClass = new MyClass();
}
}
}
}
public static string GetValue(int key)
{
return _myClass.GetValue(key);
}
}
Instance class created from the static class:
public class MyClass
{
private Dictionary<int, Guid> _valuesDict = new Dictionary<int, Guid>();
public MyClass()
{
for (int i = 0; i < 10000; i++)
{
_valuesDict.Add(i, Guid.NewGuid());
}
}
public string GetValue(int key)
{
if (_valuesDict.TryGetValue(key, out Guid value))
{
return value.ToString();
}
return string.Empty;
}
}
Should I lock when initializing private static fields from within static constructor?
Let's not bury the lede here:
Never lock in a static constructor. Static constructors are already locked by the framework so that they run on one thread exactly once.
This is a special case of a more general bit of good advice: never do anything fancy with threads in a static constructor. The fact that static constructors are effectively locked, and that lock can be contested by any code that accesses your type, means that you can very quickly get into deadlocks that you did not expect and are hard to see. I give an example here: https://ericlippert.com/2013/01/31/the-no-lock-deadlock/
If you want lazy initialization, use the Lazy<T> construct; it was written by experts who know how to make it safe.
Are my private static fields thread safe when the field is initialized on declaration?
Thread safety is the preservation of program invariants when program elements are called from multiple threads. You haven't said what your invariants are, so it is impossible to say if your program is "safe".
If the invariant you are worried about is that the static constructor is observed to run before the first static method is executed, or the first instance is created, of a type, C# guarantees that. Of course, if you write crazy code in your static constructor, then crazy things can happen, so again, try to keep your static constructors very simple.
fields of static class are not thread safe by default and should avoid unless it is just for read purpose.
Here down side is "lock" as well, it will create serialized processing in multi threaded environment.
public static class MyStaticClass
{
private static MyClass _myClass;
private static object _lockObj;
static MyStaticClass()
{
_myClass = new MyClass();
_lockObj = new object();
}
public static string GetValue(int key)
{
return _myClass.GetValue(key);
}
public static void SetValue(int key)
{
lock(_lockObj)
{
_myClass.SetValue(key);
}
}
}
Your second version is preferable. You can lock it down a little bit more by making your field readonly:
public static class MyStaticClass
{
private static readonly MyClass _myClass = new MyClass();
public static string GetValue(int key)
{
return _myClass.GetValue(key);
}
}
Your intent appears to be that _myClass is initially set to an instance of MyClass and never set to another. readonly accomplishes that by specifying that it can only be set once, either in a static constructor or by initializing it as above. Not only can another thread not set it, but any attempt to change it will result in a compiler error.
You could omit readonly and just never set _myClass again, but readonly both communicates and enforces your intent.
Here's where it gets trickier: Your reference to an instance of MyClass is thread safe. You don't have to worry about whether various threads will replace it with a different instance (or set it to null), and it will be instantiated before any threads attempt to interact with it.
What this does not do is make MyClass thread safe. Without knowing what it does or how you interact with it, there's no way for me to say what the needs or concerns are.
If that is a concern, one approach is to use a lock to prevent concurrent access that shouldn't occur, exactly as #Mahi1722 demonstrated. I'm including the code from that answer (not to plagiarize, but if anything happens to that answer then this one will refer to an answer that doesn't exist.)
public static class MyStaticClass
{
private static MyClass _myClass = new MyClass();
private static object _lockObj = new object();
public static string GetValue(int key)
{
return _myClass.GetValue(key);
}
public static void SetValue(int key)
{
lock(_lockObj)
{
_myClass.SetValue(key);
}
}
}
Both methods that interact with _myClass lock using _lockObject which means that any execution of either will block while another thread is executing either.
That's a valid approach. Another is to actually make MyClass thread safe, either by using concurrent collections or implementing such locks within that class. That way you don't have to use lock statements in every class that uses an instance of MyClass. You can just use it knowing that it manages that internally.
Both are correct,
but there is no need to lock inside static constructor.
So, i will choose the first option, it is shorter and clearer
I've read this thread "When is a static constructor called in C#" including the Programming Guide.
But is there any way to use a static constructor WITH a parameter?
I see the problem, that the static constructor is invoked bevor the first instance is created. I search for any smart solution/workaraound.
Here an example:
public class Bus
{
protected static readonly DateTime globalStartTime;
protected static readonly int FirstBusNumber;
protected int RouteNumber { get; set; }
static Bus(/*int firstBusNumber*/)//Error if uncomment: The static constructor must be parameterless
{
//FirstBusNumer = firstBusNumber;
globalStartTime = DateTime.Now;
Console.WriteLine($"The First Bus #{FirstBusNumber} starts at global start time {globalStartTime.ToLongTimeString()}");
}
public Bus(int routeNum)
{
RouteNumber = routeNum;
Console.WriteLine($"Bus #{RouteNumber} is created.");
}
public void Drive()
{
var elapsedTime = DateTime.Now - globalStartTime;
Console.WriteLine("{0} is starting its route {1:N2} minutes after the first Bus #{2}.",
RouteNumber,
elapsedTime.TotalMilliseconds,
FirstBusNumber
);
}
}
...
var bus1 = new Bus(71);
var bus2 = new Bus(72);
bus1.Drive();
System.Threading.Thread.Sleep(25);
bus2.Drive();
System.Console.WriteLine("Press any key to exit.");
System.Console.ReadKey();
Notice:
Following code is not an acceptable solution.
public Bus(int routeNum)
{
if (FirstBusNumber < 1)
FirstBusNumber = routeNum;
// ...
}
As per MSDN,
A static constructor is called automatically to initialize the class
before the first instance is created. Therefore you can't send it any parameters.
But you can create a method static to init your static values.
Check fiddle https://dotnetfiddle.net/4fnahi
public class Program
{
public static void Main()
{
Bus.Init(0);
Bus bus1 = new Bus(71);
Console.WriteLine(Bus.FirstBusNumber); // it prints 71 as your expected
}
}
public class Bus
{
public static int FirstBusNumber;
public static void Init(int firstBusNumber) => FirstBusNumber = firstBusNumber;
public Bus(int routeNum)
{
if (FirstBusNumber < 1)
FirstBusNumber = routeNum;
}
}
Firstly your example is from Microsoft docs, you can read more [here]
You, can't create a static constructor in c#. If you want specific type behavior you opt to instance class. There is a workaround, you can create a static method that settings static members, but you will need remember to use it explicitly.
Static relate to type itself. Ensure that your static constructor set static globalStartTime for this type once, it initializes the class before the first instance is created
You should really rethink if you need a static construct with a parameter.
I'm working on very simple Roguelike game (just for myself) and get a question:
As it is not possible to create a cross-class struct-object (entity in the game case) that could be accessible from any class of my program, what to use to create a cross-class object? I was thinking of something like storing all newly created object (enities) in a static object array, but I guess there is more simple solution on this problem.
Question itself: How to create a cross-class accessible object(s) with your own properties?
Thanks everybody, I found what I was searching for.
It seems like you tried passing around a value type (a struct) between different classes and you noticed that when you update the value in one place it doesn't change the value in another place.
That's the basic difference between value types and reference types.
If you are creating the struct yourself you may want to instead define it as a class.
If not, you could wrap all your structs in a class and pass the class around as your state object.
If all you have is simply a list of the same type of struct (like Points), just pass the List itself around. C# collections are implemented as classes.
public class GameState
{
public Point PlayerLocation { get; set; }
public List<Point> BulletPoints { get; set; }
public double Health { get; set; }
}
Now you can create a GameState and pass it around to different classes:
public class Game
{
private GameState _state = new GameState();
private BulletUpdater _bulletUpdater = new BulletUpdater();
public void Update()
{
_bulletUpdater.UpdatePoints(_state);
// Points have now been modified by another class, even though a Point is a struct.
}
}
public class BulletUpdater
{
public void UpdatePoints(GameState state)
{
for (int i = 0; i < state.BulletPoints.Count; i++)
{
Point p = state.BulletPoints[i];
state.BulletPoints[i] = new Point(p.X + 1, p.Y + 1);
}
}
}
Just remember in the above code if I were to write:
Point p = state.BulletPoints[i];
p.X += 1;
p.Y += 1;
That wouldn't affect the original point! When you read a value type from a list or from a class into only copies the value into a local variable. So in order to reflect your changes in the original object stored inside the reference type you need to overwrite it like so:
state.BulletPoints[i] = p;
This same principal is why the following also will not work:
state.PlayerLocation.X += 5; // Doesn't do anything
state.PlayerLocation.Y += 5; // Also doesn't do anything
The compiler would tell you in this case that you are doing something wrong. You are only modifying the returned value of the property, not the backing field itself. You have to write it like so:
state.PlayerLocation = new Point(state.PlayerLocation.X + 5, state.PlayerLocation.Y + 5); // This works!
You can do the following:
Using IoC Framework, like Ninject. You can setup Ninject to create single instance for all usages.
The other option is to use Singleton pattern design pattern
And the third one is to use static property
It sounds like you want to use the Singleton pattern:
http://en.wikipedia.org/wiki/Singleton_pattern
Here is an example of what this would look like in C#:
public class Singleton
{
static Singleton()
{
Instance = new Singleton();
}
public static Singleton Instance { get; private set; }
}
It's possible. What about public and static class?
public static class CrossClassObject
{
public static object MyProperty { get; set; }
public static void MyMethod() {}
}
Of course this class should be placed in the same namespace that other ones.
How to use it?
class OtherClassInTheSameNamespace
{
private void SomeMethod()
{
var localVariable = CrossClassObject.MyProperty; // get 'cross-class' property MyProperty
CrossClassObject.MyMethod(); // execute 'cross-class' method MyMethod()
}
}
No idea what you are trying to achieve... but if you want a list of objects accessible 'cross-class', just make a static class with a list of objects and then when you reference your class from any other class, you will have access to its list of objects. Here is something like that:
public static class ObjectController
{
private static IList<object> existingObjects;
public static IList<object> ExistingObjects
{
get
{
if (existingObjects == null)
{
existingObjects = new List<object>();
}
}
}
}
public class MyObject
{
public MyObject()
{
ObjectController.ExistingObjects.Add(this);
}
public void Delete()
{
ObjectController.ExistingObjects.Remove(this);
}
}
Then you can add stuff like
MyObject newObj = new MyObject();
//// other stuff... This object should now be visible to whatever other class references ObjectController
newObj.Delete();
I have created a class that needs to alter a variable's value when it is instantiated.
Example:
In my LrgDialogBox class I might have:
public LrgDialogBox(ref oldResult)
{
// bunch of code
UserInput();
}
public UserInput()
{
newResult=false;
}
In my main class I create an object of my LrgDialogBox called lrgDia then I type:
lrgDia = new LrgDialogBox(ref result);
if (result==true) this.exit;
I basically need to know how to make the reference variable "oldResult" private in my LrgDialogBox class, so that any method can alter its value so it can be used in my main class. Hopefully without changing the parameters of my other methods. Please help.
Kris
There isn't any way for you to meaningfully store the reference parameter that is passed in and be able to modify its value later. What you need to do is add in another layer of indirection; create a reference type that holds onto the value that you really care about. Pass around references to that type, and then all of those references are indirectly pointing to a single value.
The implementation of such a wrapper is simple:
public class Wrapper<T>
{
public T Value { get; set; }
}
You can now create a class that accepts a Wrapper<bool> in the constructor, and then modifies the value within that wrapper at a later point in time.
public class Foo
{
private Wrapper<bool> flag;
public Foo(Wrapper<bool> flag)
{
this.flag = flag;
}
public void Bar()
{
flag.Value = false;
}
}
The other option available to you, since you are, in this case, only calling the method from within the constructor, is to simply have your other method return its value, rather than setting a private field. This would be the preferred design:
public class LrgDialogBox
{
public LrgDialogBox(ref bool oldResult)
{
// bunch of code
oldResult = UserInput();
}
public bool UserInput()
{
return false;
}
}
Just use a private variable to work with during the processing.
private bool _newResult;
public LrgDialogBox(ref bool oldResult)
{
// bunch of code
_newResult = oldResult;
UserInput();
oldResult = _newResult;
}
private void UserInput()
{
_newResult = false;
}
We need to use an unmanaged library in our code that has static methods. I'd like to introduce the library operation as a dependency in my code. And apart from having static methods, the library has an initialization method and a settings method, both are global. So I can't just wrap this in an instance class, because if one instance changes a setting, all other instances will be affected, and if one instance gets initialized, all other instances will be reinitialized.
I thought about introducing it as a singleton class. This way it will be in an instance class, but there will only be one instance thus I won't have to worry about changing the settings or initialization. What do you think about this approach? I'm pretty new to the dependency injection pattern and I'm not sure if the singleton pattern is a good solution? What would your solution be to a similar case?
Edit: The initialization takes a parameter too, so I can't just lock the method calls and re-initialize and change settings every time it is called.
Edit 2: Here are the signatures of some methods:
public static void Initialize(int someParameter)
// Parameter can only be changed by re-initalization which
// will reset all the settings back to their default values.
public static float[] Method1(int someNumber, float[] someArray)
public static void ChangeSetting(string settingName, int settingValue)
If you only need to set the settings once at start up, then I would recommend making a non-static wrapper class which does all the initialization of the static class in its own static constructor. That way you can be assured that it will only happen once:
public class MyWrapper
{
public MyWrapper()
{
// Do any necessary instance initialization here
}
static MyWrapper()
{
UnManagedStaticClass.Initialize();
UnManagedStaticClass.Settings = ...;
}
public void Method1()
{
UnManagedStaticClass.Method1();
}
}
However, if you need to change the settings each time you call it, and you want to make your instances thread-safe, then I would recommend locking on a static object so that you don't accidentally overwrite the static settings while they're still in use by another thread:
public class MyWrapper
{
public MyWrapper()
{
// Do any necessary instance initialization here
}
static MyWrapper()
{
UnManagedStaticClass.Initialize();
}
static object lockRoot = new Object();
public void Method1()
{
lock (lockRoot)
{
UnManagedStaticClass.Settings = ...;
UnManagedStaticClass.Method1();
}
}
}
If you need to pass initialization parameters into your class's instance constructor, then you could do that too by having a static flag field:
public class MyWrapper
{
public MyWrapper(InitParameters p)
{
lock (lockRoot)
{
if (!initialized)
{
UnManagedStaticClass.Initialize(p);
initialized = true;
}
}
}
static bool initialized = false;
static object lockRoot = new Object();
public void Method1()
{
lock (lockRoot)
{
UnManagedStaticClass.Settings = ...;
UnManagedStaticClass.Method1();
}
}
}
If you also need to re-initialize each time, but you are concerned about performance because re-initializing is too slow, then the only other option (outside of the dreaded singleton) is to auto-detect if you need to re-initialize and only do it when necessary. At least then, the only time it will happen is when two threads are using two different instances at the same time. You could do it like this:
public class MyWrapper
{
public MyWrapper(InitParameters initParameters, Settings settings)
{
this.initParameters = initParameters;
this.settings = settings;
}
private InitParameters initParameters;
private Settings settings;
static MyWrapper currentOwnerInstance;
static object lockRoot = new Object();
private void InitializeIfNecessary()
{
if (currentOwnerInstance != this)
{
currentOwnerInstance = this;
UnManagedStaticClass.Initialize(initParameters);
UnManagedStaticClass.Settings = settings;
}
}
public void Method1()
{
lock (lockRoot)
{
InitializeIfNecessary();
UnManagedStaticClass.Method1();
}
}
}
I would use a stateless service class, and pass in state info for the static class with each method call. Without knowing any details of you class, I'll just show another example of this with a c# static class.
public static class LegacyCode
{
public static void Initialize(int p1, string p2)
{
//some static state
}
public static void ChangeSettings(bool p3, double p4)
{
//some static state
}
public static void DoSomething(string someOtherParam)
{
//execute based on some static state
}
}
public class LegacyCodeFacadeService
{
public void PerformLegacyCodeActivity(LegacyCodeState state, LegacyCodeParams legacyParams)
{
lock (_lockObject)
{
LegacyCode.Initialize(state.P1, state.P2);
LegacyCode.ChangeSettings(state.P3, state.P4);
LegacyCode.DoSomething(legacyParams.SomeOtherParam);
//do something to reset state, perhaps
}
}
}
You'll have to fill in the blanks a little bit, but hopefully you get the idea. The point is to set state on the static object for the minimum amount of time needed, and lock access to it that entire time, so no other callers can be affected by your global state change. You must create new instances of this class to use it, so it is fully injectable and testable (except the step of extracting an interface, which I skipped for brevity).
There are a lot of options in implementation here. For example, if you have to change LegacyCodeState a lot, but only to a small number of specific states, you could have overloads that do the work of managing those states.
EDIT
This is preferable to a singleton in a lot of ways, most importantly that you won't be able to accumulate and couple to global state: this turns global state in to non-global state if it is the only entry point to your static class. However, in case you do end up needing a singleton, you can make it easy to switch by encapsulating the constructor here.
public class LegacyCodeFacadeService
{
private LegacyCodeFacadeService() { }
public static LegacyCodeFacadeService GetInstance()
{
//now we can change lifestyle management strategies later, if needed
return new LegacyCodeFacadeService();
}
public void PerformLegacyCodeActivity(LegacyCodeState state, LegacyCodeParams legacyParams)
{
lock (_lockObject)
{
LegacyCode.Initialize(state.P1, state.P2);
LegacyCode.ChangeSettings(state.P3, state.P4);
LegacyCode.DoSomething(legacyParams.SomeOtherParam);
//do something to reset state, perhaps
}
}
}