Okay, I am way outside my comfort zone here and am struggling with new concepts but I hope I can make myself clear.
As I understand it, global variables are very bad in C# (and are dangerous in general) but I don't really want to get into that debate. After some research I am led to believe that Singletons can help. Please feel free to offer alternatives here if that is wrong with the situation I describe below.
What I am trying to do is create a dynamic multi-dimensional array which will contain numerical data. This matrix will be varying in size and must be created during runtime (I am pulling data from a logging device through a GUI).
What I see being a solution is to create a class which has a variable which can I can get and set but with a dynamic size.
public class mySingleton
{
public static int dataSize { get; set; }
public double[] dataSet = new double[dataSize] { get; set; }
}
Something to this effect but obviously this is wrong and does not work. I have been trying to research how to initialize an array at runtime but cannot figure it out, but I also feel like I don't know which terms to search. Any help?
What you probably want to do is use explicit (rather than implicit) backing fields so that you can add logic to your getter and setter. Something like this:
public class mySingleton
{
private static int _dataSize; // you might want to set this to some sensible default
public static int DataSize
{
get { return _dataSize; }
set
{
_dataSize = value;
_dataSet = null; // changing the size will implicitly clear the array - but you could write code to resize if you really wanted to
}
}
private static double[] _dataSet;
public static double[] DataSet
{
get
{
if (_dataSet == null)
{
_dataSet = new double[_dataSize];
}
return _dataSet;
}
// you can include a setter if you want to let the consumer set the dataset directly - in which case it should update the _dataSize field.
}
}
You may want to initialize the array in response to the set method on your dataSize property. You won't be able to use the quick "autofill" properties ("get; set;"), but that way you will be able to initialize the data set as soon as a user sets the data size.
So something like this:
public class mySingleton
{
private static int _dataSize;
public static int dataSize {
get {return _dataSize;}
set {
_dataSize = value;
dataSet = new double[value];
}
}
public double[] dataSet { get; private set; }
}
In general, to set a static property of a class, you can use a static constructor (http://msdn.microsoft.com/en-us/library/k9x6w0hc(v=vs.80).aspx) or control the flow of access to the class/data in a way that you can set up the static members before someone else needs to use them.
You can create an array of dynamic size easily:
double[] array = new double[size];
size can be any arbitrary expression of type int. So your code would look like this:
class ArrayHolder { public static double[] Value; } //global state
//set the global state somewhere else in your code:
var size = DetermineSize();
double[] array = new double[size];
ArrayHolder.Value = array; //publish globally
After having initialized the array it is available in the entire program. Arrays are reference types so there is no needless data copying here.
Sidenote: Why would you prefer a singleton to a static variable? Often they have the same pros and cons (IOW no meaningful difference). In my example I just used a static variable.
I am not sure if a Singleton suits best for your approach, but anyway, here is a Singleton Implementation:
public class MatrixSingleton
{
private static readonly MatrixSingleton instance = new MatrixSingleton();
static MatrixSingleton()
{
}
private MatrixSingleton()
{
this.Data = new List<Tuple<double, double>>();
}
public static MatrixSingleton Instance
{
get { return instance; }
}
public List<Tuple<double, double>> Data;
}
and the using of it
MatrixSingleton matrixSingleton = MatrixSingleton.Instance;
matrixSingleton.Data.Add(new Tuple<double, double>(1.1, 2.2));
For more information about the Singleton pattern these links might help:
http://braindrivendevelopment.com/2013/05/04/simplify-singleton-pattern/
http://www.csharpindepth.com/Articles/General/Singleton.aspx
Related
In my project I'm using some static variables which I use for storing values during the running lifetime of the application. Now, 99% of the time I'm only reading these values but from time to time I also need to update them and this will happen from different threads.
When thinking about what might happen with two different threads trying to access the same property e.g. concurrent read/write, I started to conclude that some form of synchronization would needed in order to avoid unexpected values being returned between different process or some risk of race conditions.
In essence I needed to derive a single source of truth. I realize that some properties are atomic like booleans, but my methodology mostly applies for the purpose of strings.
One of the challenges is that these static variables are referenced in many places and between different classes, so I also had to figure out an efficient way to solve this challenge without lots of code re-write.
I've decided to use concurrent dictionaries:
public static readonly ConcurrentDictionary<string, string> AppRunTimeStringDictionary = new();
public static readonly ConcurrentDictionary<string, int> AppRunTimeIntegerDictionary = new();
public static readonly ConcurrentDictionary<string, bool> AppRunTimeBooleanDictionary = new();
In my program.cs file, during the earliest stages of startup I simply add all of the properties needed for the running app:
DeviceProvisioning.AppRunTimeBooleanDictionary.TryAdd("UseGpsReceiver", false);
DeviceProvisioning.AppRunTimeStringDictionary.TryAdd("Latitude", String.Empty);
DeviceProvisioning.AppRunTimeStringDictionary.TryAdd("Longitude", String.Empty);
Then in one of my classes I hard code these properties:
public static bool? UseGpsReceiver
{
get
{
if (AppRunTimeBooleanDictionary.TryGetValue("UseGpsReceiver", out var returnedValue))
return returnedValue;
return null;
}
}
public static string? Latitude
{
get
{
if (AppRunTimeStringDictionary.TryGetValue("Latitude", out var returnedValue))
return returnedValue;
return null;
}
}
public static string? Longitude
{
get
{
if (AppRunTimeStringDictionary.TryGetValue("Longitude", out var returnedValue))
return returnedValue;
return null;
}
}
Now for updating these properties, which happens rarely but will be done every now and then, I'm updating these in just one location i.e. using a single method. This way I can use this common method and simply add more prperties to the switch case over time.
public static void SetRunTimeSettings(string property, object value)
{
switch (property)
{
case "UseGpsReceiver":
// code block
if (AppRunTimeBooleanDictionary.TryGetValue("UseGpsReceiver", out var useGpsReceiver))
{ AppRunTimeBooleanDictionary.TryUpdate("UseGpsReceiver", (bool)value, useGpsReceiver); }
break;
case "Latitude":
// code block
if (AppRunTimeStringDictionary.TryGetValue("Latitude", out var latitude))
{ AppRunTimeStringDictionary.TryUpdate("Latitude", (string)value, latitude); }
break;
case "Longitude":
// code block
if (AppRunTimeStringDictionary.TryGetValue("Latitude", out var longitude))
{ AppRunTimeStringDictionary.TryUpdate("Latitude", (string)value, longitude); }
break;
}
}
If I want to update a property then I simply invoke the method as such:
MyClassName.SetRunTimeSettings("UseGpsReceiver", true);
MyClassName.SetRunTimeSettings("Latitude", "51.1234");
MyClassName.SetRunTimeSettings("Longitude", "51.5678");
Because the properties themselves are public static then I can use the getter from anywhere in the app.
From my initial testing, everything seems to work.
Perceived advantages in this approach:
Using a separate dictionary for each type of property collection i.e. strings/integers etc, means I can simply add more properties to the dictionary any time in the future without the need for referencing a model class in the dictionary, as opposed to the dictionary below:
public static readonly ConcurrentDictionary<string, myModelClass> AppRunTimeStringDictionary = new();
Use of the concurrent dictionary (my understanding) is that any process trying to read the property value from the dictionary will always get the latest value, if a property is being updated then I have less risk in reading an old value. Not such an issue for structured logging but if I was storing keys/secrets/connection strings or anything else, reading an old value might stop some process from being able to function correctly.
Using the concurrent dictionary means I don't have to hand craft my own locking mechanisms, which many people seem not to like doing.
Dictionary applies its own internal locks on the individual objects, so any property not being updated can still be read by other processes without much delay.
If the public static getter ever returned a null value, my thoughts are it would be better to return a null value rather than returning the wrong value. I could always implement some kind of polly or retry mechanism somewhere from the calling process, some short delay before trying to retrieve the property value again (by which time it should have been updated from the other thread that was currently updating it)
Appreciate there will be other ways to approach this, so really what I'm asking here is whether anyone sees any issue in my approach?
I'm not planning to add that many properties to each dictionary, I just want a way to ensure that reads and writes are happening with some form of synchronization and order.
Your SetRunTimeSettings is awful. It relies on methods that follow the Try* pattern, but it itself does not. Also doing a TryGetValue just to then be able to call TryUpdate is just throwing away all of the value of Try* operators anyway. It's a hack.
And you have a clear bug in the code for the "Longitude" case - you're updating "Latitude" inside.
I'd suggest going old school and just do this:
private static bool? _UseGpsReceiver;
private readonly static object _UseGpsReceiverLock = new();
public static bool? UseGpsReceiver
{
get { lock (_UseGpsReceiverLock) return _UseGpsReceiver; }
set { lock (_UseGpsReceiverLock) _UseGpsReceiver = value; }
}
private static string? _Latitude;
private readonly static object _LatitudeLock = new();
public static string? Latitude
{
get { lock (_LatitudeLock) return _Latitude; }
set { lock (_LatitudeLock) _Latitude = value; }
}
private static string? _Longitude;
private readonly static object _LongitudeLock = new();
public static string? Longitude
{
get { lock (_LongitudeLock) return _Longitude; }
set { lock (_LongitudeLock) _Longitude = value; }
}
If you don't want to repeat all of the locks then maybe a Locked<T> class might be of use:
public struct Locked<T>
{
public Locked(T value)
{
_value = value;
}
private T _value;
private readonly object _gate = new();
public T Value
{
get { lock (_gate) return _value; }
set { lock (_gate) _value = value; }
}
}
Then you can write this:
private static Locked<bool?> _UseGpsReceiver;
public static bool? UseGpsReceiver
{
get { return _UseGpsReceiver.Value; }
set { _UseGpsReceiver.Value = value; }
}
private static Locked<string?> _Latitude;
public static string? Latitude
{
get { return _Latitude.Value; }
set { _Latitude.Value = value; }
}
private static Locked<string?> _Longitude;
public static string? Longitude
{
get { return _Longitude.Value; }
set { _Longitude.Value = value; }
}
If you are only setting a single string / int / bool at a time, then you don't need to any thread safety. If you are assigning any single value smaller than a machine word, any reading thread will either see the before value or the after value.
However it looks like you intend to set three values at the same time;
MyClassName.SetRunTimeSettings("UseGpsReceiver", true);
MyClassName.SetRunTimeSettings("Latitude", "51.1234");
MyClassName.SetRunTimeSettings("Longitude", "51.5678");
And I assume you want any reader to see either the old values or the new values. In this case you would need some thread synchronisation around every read / write. Which your current code doesn't have.
You could instead store the three values in a class, then update the reference to that instance in one write operation.
public class GpsSettings{
public bool UseGpsReceiver { get; init; }
public double Latitude { get; init; }
public double Longitude { get; init; }
public static GpsSettings Current;
}
...
// write
GpsSettings.Current = new GpsSettings {
UseGpsReceiver = true,
Latitude = 51.1234,
Longitude = 51.5678
};
// read
var gps = GpsSettings.Current;
var location = $"{gps.Latitude}, {gps.Longitude}";
// but never do this;
var location = $"{GpsSettings.Current.Latitude}, {GpsSettings.Current.Longitude}";
Not everyone would agree with me on this one but my personal approach would be to have a single dictionary of the following type:
Dictionary<string, object>
Wrapped in a separate class with the following methods such as AddValue, GetValue, HasKey, HasValue, and UpdateValue with lock statements. Also notice that you'll have to use somewhat generic methods in order to be able to retrieve the value with the actual type and a default value. For example:
public static T GetValue<T>(string key, T defaultValue)
Also, I don't see a problem with your approach but if you want to synchronize things then you'll need n dedicated locks for n dictionaries which I don't think is a clean way; unless I'm missing something, and of course registering multiple dictionaries in design time can be a headache.
Alternatively to using multiple ConcurrentDictionary<string, T> collections, or a single ConcurrentDictionary<string, object>, or the Locked<T> struct shown in Enigmativity's answer, you could just store the values in immutable and recyclable Tuple<T> instances, and store these in private volatile fields:
private static volatile Tuple<bool?> _UseGpsReceiver;
public static bool? UseGpsReceiver
{
get { return _UseGpsReceiver?.Item1; }
set { _UseGpsReceiver = new(value); }
}
private static volatile Tuple<string> _Latitude;
public static string Latitude
{
get { return _Latitude?.Item1; }
set { _Latitude = new(value); }
}
private static volatile Tuple<string> _Longitude;
public static string Longitude
{
get { return _Longitude?.Item1; }
set { _Longitude = new(value); }
}
Pros: Both the reading and the writing are lock-free. An unlimited number of readers and writers can read and update the values at the same time, without contention.
Cons: Every time a value is updated, a new Tuple<T> is instantiated, adding pressure on the .NET garbage collector. This reduces the appeal of this approach in case the values are updated too frequently. Also if you have dozens of properties like these, it might be easy to introduce subtle bugs by omitting the important volatile keyword by mistake.
I am asking a beginner level question. Though I am working in MVC but I am really confused with a simple concept and that is "Properties". There are lot of questions that
I have already gone through but there is surely a doubt in mind and did'nt able to clear it up.
Actually c# properties used for getting and setting the value to the private fields.
Like
Public class MyClass
{
private int number;
public int Number{
get{ return this.number;}
set{ number=Value }
}
}
class Program
{
static void Main()
{
MyClass example = new MyClass();
example.Number = 5; // set { }
Console.WriteLine(example.Number); // get { }
}
}
Now , the value is assigned to property also and to the variable also. Right?
Now , here is my doubt::
When we create property in model for MVc structure, we only have
public int Number{get;set;}
If this is okay to work with then why we are creating unnecessorily one more field of private access specifier. If encapsulation is the reason for that or hiding the data then why not in model in MVC?
Actually, in the above class example can I only use
Console.WriteLine(example.number);
after declaring it public?
Then what's the use of creating property over here?
Properties can be used to a store and retrieve values from a backing field (number in your case) directly as in your first sample. But property getters and setters are ordinary blocks of code that you can use as you want. So you don't have to assign a backing field, but can derive the value of a property also from another property in a getter, e.g.
public int NumberTimesTwo
{
get
{
return Number * 2;
}
}
However, as a common scenario is to have a property retrieve and assign the value of a backing field, there is a shortcut that you can use:
public int Number { get; set; }
In this case, the compiler automatically creates a private backing field that the property retrieves in the getter and assigns in the setter, so the code is equivalent to the following, but less to type:
private int _number;
public into Number
{
get
{
return _number;
}
set
{
_number = value;
}
}
As the backing field is also private, you cannot access it from outside of the class directly.
private int myVar;
public int MyProperty
{
get { return myVar; }
set { myVar = value; }
}
You are implementing Encapsulation by using MyProperty, which is public to access myVar which is private and is accessible only in the block where defined, that is, your class and not outside it.
Btw, in what way does this QA not answer your question? Try going through this for further reference.
My problem, narrowed down to a simple explaination, is the following:
I have a class which needs to work with a number (without changing it) which is subject to change. This number doesn't necessarily come from another class, and it can be anything.
But I'd like to only "give" it to the class once, instead of constantly having to call update methods or having to create a wrapper (since again, as I said, this should work with any kind of number and having to wrap up everything is kind of unpratical).
Here's some code, hoping it helps:
public class SimpleExample
{
int value;
public SimpleExample(int variableOfWhichINeedAReference)
{
//Of course this won't work, but I'll keep it simple.
value = variableOfWhichINeedAReference;
}
public void DisplayValue()
{
print(value);
}
}
public class RandomClass
{
int myValue = 10;
SimpleExample s = new SimpleExample(myValue);
public void WorkWithValue()
{
myValue++;
}
public void Display()
{
print(foo);
print(bar);
s.DisplayValue();
}
}
Now, the problem seems pretty obvious: If I instantiate a SimpleExample and give it a variable as a parameter, it will get its value rather than a reference to it.
Is there a simple enough way that can avoid me the creation of a wrapper? Thanks.
Make a really simple class:
class Ref<T>
{
public T Value;
public Ref<T>()
{
}
public Ref<T>(T value)
{
this.Value = value;
}
}
Then use it like this:
class A
{
Ref<int> x;
public A(Ref<int> x)
{
this.x = x;
}
public void Increment()
{
x.Value++;
}
}
...
Ref<int> x = new Ref<int>(7);
A a = new A(x);
a.Increment();
Debug.Assert(x.Value == 8);
Note that the Ref<T> class here is a reference to a value - not a reference to a variable. If you want a reference to a variable, use Eric Lippert's solution (as pointed out by Filip).
So what you want is not an int, but rather a way of getting an int at some point in time. There are several ways of doing this, one of which is to have your object accept a Func<int>. Then the code can pass in a method that returns the current value of...whatever, rather than the value at the time SimpleExample is created. Using a lambda to close over a variable makes doing this much easier as well.
public class SimpleExample
{
Func<int> func;
public SimpleExample(Func<int> func)
{
this.func = func;
}
public void DisplayValue()
{
print(func());
}
}
public class RandomClass
{
int myValue = 10;
SimpleExample s;
public RandomClass()
{
s = new SimpleExample(() => myValue);
}
public void WorkWithValue()
{
myValue++;
}
public void Display()
{
print(foo);
print(bar);
s.DisplayValue();
}
}
There is no standard wrapper for the purpose you seek, though a single-element array could be used for that purpose. Alternatively, one could define a simple wrapper type:
public class ExposedValueHolder<T> { public T Value; } // Really simple class, eh?
and then use an ExposedValueHolder<YourStructType> to wrap your object. It's not possible in general to capture something passed as an arbitrary ref parameter, since objects may live indefinitely but byrefs (the things which are actually passed when using ref parameters) may die any time after function they're passed to goes out of scope.
I have a static string class for my database so that I always spell the tables and columns they way they were designed.
I've currently got about 500 lines of code in this one class, but here is a short example:
public const string PURCHASING = "PURCHASING";
public const string SCHED_PURCH = "SCHED/PURCH";
public const string SCHEDULING = "SCHEDULING";
To create a readonly static string array of the "Clerk" department, I use this static declaration:
public static string[] CLERK_DEPT {
get {
return new string[] { PURCHASING, SCHEDULING, SCHED_PURCH };
}
}
There are many lines of code like this in my database strings class.
Today, I happened across this active post where someone was doing something very similar:
How do I prevent the modification of a private field in a class?
The answer there provided a way to provide a readonly string array that I had not considered before:
You must return a copy of your array.
public String[] getArr() {
return arr == null ? null : Arrays.copyOf(arr, arr.length);
}
That has me wondering now if someone out here knows of a more efficient way of passing back my readonly string array.
I must admit that I've always abhorred the idea of the return new string[] in my code.
So, is there? ...a more efficient and cleaner way of doing this or have I already created the best solution?
There's no such thing as an immutable array, basically.
If you trust all your callers, you could tell them not to mutate the array. An alternative is to provide a read-only wrapper:
private static readonly ReadOnlyCollection<string> clerkDepartments =
new ReadOnlyCollection<string>(
new[] { "PURCHASING", "SCHED/PURCH", "SCHEDULING" });
public static readonly ReadOnlyCollection<string> ClerkDepartments
{ get { return clerkDepartments; } }
Note that although ReadOnlyCollection<T> isn't a totally immutable collection, only code with access to the underlying collection could change it - and as the only code which "knows" about the array is the initializer which passes it to the constructor, you're basically safe unless someone cracks out reflection :)
Perhaps use a ReadOnlyCollection?
http://msdn.microsoft.com/en-us/library/ms132474.aspx
How do I create a class library where I can get and set like the IIS Session object where I use var x = objectname("key") to get the value or objectname("key") = x to set the value?
Normally I just have a static class that wraps my session data and makes it type safe like:
public static class MySessionHelper
{
public static string CustomItem1
{
get { return HttpContext.Current.Session["CustomItem1"] as string; }
set { HttpContext.Current.Session["CustomItem1"] = value; }
}
public static int CustomItem2
{
get { return (int)(HttpContext.Current.Session["CustomItem2"]); }
set { HttpContext.Current.Session["CustomItem2"] = value; }
}
// etc...
}
Then when I need to get or set an item you would just do the following:
// Set
MySessionHelper.CustomItem1 = "Hello";
// Get
string test = MySessionHelper.CustomItem1;
Is this what you were looking for?
EDIT: As per my comment on your question, you shouldn't access the session directly from pages within your application. A wrapper class will make not only make the access type safe but will also give you a central point to make all changes. With your application using the wrapper, you can easily swap out Session for a datastore of your choice at any point without making changes to every single page that uses the session.
Another thing I like about using a wrapper class is that it documents all the data that is stored in the session. The next programmer that comes along can see everything that is stored in the session just by looking at the wrapper class so you have less chance of storing the same data multiple times or refetching data that is already cached in the session.
I guess, you could use a generic dictionary like Dictionary<string, Object> or something similar to achieve this effect. You would have to write some wrapper code to add an Object when accessing a non-existend item by for example a custom default property in your Wrapper.
You could use some thing like this
public class Session
{
private static Dictionary<string, object> _instance = new Dictionary<string, object>();
private Session()
{
}
public static Dictionary<string, object> Instance
{
get
{
if(_instance == null)
{
_instance = new Dictionary<string, object>();
}
return _instance;
}
}
}
And use it like this
Session.Instance["key"] = "Hello World";