Accessing Private Property value in C# 6.0 without creating it - c#

I understand that reading from the WebConfigurationManager is slow, so I want to minimize my use of it.
Say I have the following readonly property in my code:
public string SiteLogo {
get {
return WebConfigurationManager.AppSettings["SITE_LOGO"];
}
}
In C# 6.0, I can shorten this so that the "getter" has the default value:
public string SiteLogo { get; } = WebConfigurationManager.AppSettings["SITE_LOGO"];
This, it looks like, would be called every time the class is instantiated, whether that Property is ever used or not.
It looks like the most efficient call is still to declare a Private variable to use in the Property:
public string SiteLogo
{
get
{
if (String.IsNullOrEmpty(_siteLogo))
{
_siteLogo = WebConfigurationManager.AppSettings["SITE_LOGO"];
}
return _siteLogo;
}
}
private string _siteLogo;
This still requires me to create Private variables for all of my getters, which seems overly tedious.
I have discarded the idea of using a Session variable, because reading that and casting it to a String seems like it would still incur more overhead.
I would like to see is a way to Auto Assign the Private Property if it is needed.
If the compiler called each Property's Private field #this, I could use something along these lines:
public string SiteLgo
{
get
{
if (String.IsNullOrEmpty(#this))
{
#this = WebConfigurationManager.AppSettings["SITE_LOGO"];
}
return #this;
}
}
Even better, I should not ever need to explicitly tell the code block to return the Private Property, since that is the getter's job:
public string SiteLogo
{
get
{
if (String.IsNullOrEmpty(#this))
{
#this = WebConfigurationManager.AppSettings["SITE_LOGO"];
}
}
}
If a technique to do that currently exists, I don't know the name of what to call it to look it up.
Have I missed the better way to do what I am after (accessing the Private value without having to create it)?

You missed some class that was introduced in .NET 4.0: Lazy<T>:
private readonly string _siteLogo = new Lazy<string>(() => WebConfigurationManager.AppSettings["SITE_LOGO"]);
// Lazy<T>.Value will call the factory delegate you gave
// as Lazy<T> constructor argument
public string SiteLogo => _siteLogo.Value;
BTW, I wouldn't use lazy-loading for this case... at the end of the day, application settings are already loaded into memory and you aren't accessing from the file.
In fact, AppSettings is a NameValueCollection and it uses hash codes to store keys (taken from MSDN):
The hash code provider dispenses hash codes for keys in the
NameValueCollection. The default hash code provider is the
CaseInsensitiveHashCodeProvider.
In other words, accessing AppSettings has a time complexity O(1) (constant).
I would use lazy-loading if you would need to parse settings some way to avoid re-parsing them everytime.

Related

Solution for thread safe read write updates to static variables with read write synchronization

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.

Can I define a custom getter for a C# auto-implemented property (a.k.a. auto backing field)?

Note: I know how to accomplish this without using auto-implemented properties, but I'm wondering if C# has a built-in way to do this.
Let's say I have this simple example of an auto-implemented property (a.k.a. auto backing field):
public class MyClass
{
public MyClass(){}
public string MyString { get; private set; }
}
Now, I would like to return a custom exception in the getter if the auto backing field is null:
public class MyClass
{
public MyClass(){}
public string MyString
{
get
{
return [backing field] ?? throw new Exception("MyString is null");
}
private set;
} = null;
}
Do newer C# versions support something like this? Perhaps there is some syntactic sugar that I can use in place of [backing field] to access the backing field that is automatically created by the compiler?
Note on putting an exception in the getter: I know it shouldn't be a habit. But Microsoft does it occasionally; for example, the property HttpContext.Request.Form will throw an exception if the request is not of the proper content-type.
No, you can not access to backing field in this way.
You must define backing field and validate it.
public class MyClass
{
public MyClass(){}
private string? _myString
public string MyString
{
get
{
return _myString ?? throw new Exception("MyString is null");
}
private set => _myString = value;
} = null;
}
As Fred said, its better to validate it outside of property.
I'm surprised noone mentioned the field keyword, it is exactly what you are asking for (what you would use instead of [backing field] in your example). It was supposed to be shipped with C# 10. It seems it is going to be shipped with C# 11 instead (?)
Search for Field Keyword here.
Put validation in the setter and/or ensure that the constructor sets a valid/non-null default value.
Or make the property nullable to hint to the customer that they have to account for a null value possibility.
Alternatively (but less optimally for multiple reasons), make the property private and add a method for accessing it.
Strongly advise against a property get directly throwing an exception. You or the consumer will dislike the results at some point.

Auto-implemented properties and additional function

Is there a way to do something like this in C#:
public class Class2 {
public string PropertyName1 { get
{
return this; //i mean "PropertyName1"
}
set {
this = value;
DoAdditionalFunction();
}
}
Because I need to call additional function in the "set" I need to have an extra private field like
private string _propertyName1;
public string PropertyName1 { get
{
return _propertyName1;
}
set {
_propertyName1= value;
DoAdditionalFunction();
}
I don't want to use additional property like _propertyName1. Is there a way to accomplish this or any best practices?
No - if you need any behaviour other than the most trivial "set a field, return the field value", you need to write "full" properties. Automatically implemented properties are only a shorthand for trivial properties.
Note that you haven't really got an "extra" private field, in terms of the actual contents of an object - it's just that you're explicitly declaring the private field instead of letting the compiler do it for you as part of the automatically implemented property.
(It's not clear what your first property is trying to do - setting this in a class is invalid, and you can't return this from a property of type string unless you've got a conversion to string...)

How to avoid private property null check to do lazy loading?

I have a class with like 20 fields which get populated from SQL database on load. Currently I am calling load data method right after the constructor, which calls SQL proc and populate all the required fields. At times, I may not access the these 20 fields at all, I am adding additional cost of SQL call even though it was not required. So I changed all the properties to have an associated private property and when the program calls the public property, first I check the private property and if it is null that means we need to load data from sql so I call the load method. It works great, but when I see the code, there is a repeated pattern of null check and load the sql query. Is there a better way of doing this?
private string _name;
public string Name
{
get {
if (_name == null)
LoadData(); //this popultes not just but all the properties
return _name;
}
}
Btw C# now has default lazy-loaders implementation. Why not to use it, instead of providing isSomethingLoaded flags? :)
public class Bar
{
private Lazy<string> _name = new Lazy<string>(() => LoadString());
public string Name
{
get { return _name.Value; }
}
}
In case of non-static LoadString method, lazy-loader should be initialized in constructor;
Nope, this is right. Here is the wikipedia article. The overhead of the null check will be very minimal compared to unnecessary database calls. Now, if the users of the program actually use the values 99% of the time, then I would say this pattern is not needed.
Just one note of caution: If any of your values could possibly be null, then you will make unnecessary database calls. It might be better to do something like this (which will be an even quicker check since it is just a bit check):
//Constructor default to not loaded
bool isLoaded = false;
private string _name;
public string Name
{
get {
if (!isLoaded)
LoadData(); //this popultes not just but all the properties
return _name;
}
}
private LoadData()
{
//Load Data
isLoaded = true;
}
Well you could change it to:
if (!initialized)
LoadData();
And in your LoadData set initialized to true, but that really doesn't change the semantics of it.
One thing you can do is to extract if into separate method so each property contains just one additional call:
void EnsureData()
{
if (!dataLoaded)
LoadData(); //this populates all the properties
}
public string Name {
get {
EnsureData();
return _name;
}
}
I think you should consider your application structure. Why would you even instantiate the class if you are not going to be using the properties? I believe it's actually cleaner for you to call the SQL after your constructor code but only create the objects of your class if you are going to be using it. The other more flexible solution is making the LoadData public and calling it as needed from the object instance as needed.
I am in the learning process of design patterns. i have one suggestion if you load data only once you can try with singleton design pattern.
public class Singleton123
{
private static readonly string _property1 = ClassLoadData.LoadData();
public static string MyProperty1
{
get
{
return _property1;
}
}
}
public class ClassLoadData
{
public static string LoadData()
{
// any logic to load data
return "test";
}
}
Call property as below
Singleton123 obj = new Singleton123();
string stra = Singleton123.MyProperty1;
string strb = Singleton123.MyProperty1;
this property will be loaded only once.

Proper Syntax for C# Properties

Per the MSDN documentation, the following syntax is used:
// A read-write instance property:
public string Name
{
get { return name; }
set { name = value; }
}
However, the following code is generated by VS2010 automatically for a new library class:
public string Name
{
get
{
String s = (String)ViewState["Name"];
return ((s == null) ? String.Empty : s);
}
set
{
ViewState["Name"] = value;
}
}
When is it appropriate to use the ViewState syntax over the shorter example shown on MSDN?
ViewState is a feature of ASP.Net server controls that persists information across postbacks.
For simple properties that aren't in a server control, you should use an auto-implemented property:
public string Name { get; set; }
The first stores the value in a private property field inside the class, while the second (tries to) store the actual value in the ViewState.
So the 2nd is only possible when you are talking about ASP controls with viewstate enabled, which is a narrow subset of all possible cases.
A C# property is just a piece of syntactic sugar. This structure
public Foo MyValue { get ; private set ; }
is exactly as if you coded:
private Foo _myValue ;
public Foo
{
get
{
return _myValue ;
}
private set
{
this._myValue = value ;
}
}
In either case, the code that actually gets generates is pretty much this:
private Foo _myValue ;
public Foo MyValue_get()
{
return this._myValue ;
}
private Foo MyValue_set( Foo value )
{
this._MyValue = value ;
}
If you opt to instantiate your own getter/setter, then what happens in the body of the getter/setter is entirely up to you. There is no "right" or wrong: it's dependent on the needs of your program.
With respect to ViewState, ViewStateis a piece of ASP.Net. It has little do with properties one way or another. You example just exposes a ViewState item as a public read/write property.
The difference between the two is that one is just plain old C# property providing access to a (most likely) privately scoped variable in your class.
The other one is returning a value recovered from ASP.NET's ViewState.
These are two different things altogether.

Categories