Retaining a value obtained from file within the return value of a method - c#

Assuming I will need to access the values contained within a given file a small number of times, from different methods, can I include some sort of boolean value within a method to determine whether or not it is appropriate to call the file?
Lets say I have the file config.cfg. In that file, there are three values:
string/name>max|
bool/adult>yes|
int/age>20|
The method getUserName() returns the value of "max". It does this by calling the file:
using (StreamReader reader = new StreamReader(path))
{
//get line beginning with string/name here
return //string value containing name
}
Let's assume I need to use the value of name several times, as well as the values isAdult and clientAge. Rather than accessing the file over and over again, it could be much easier to save the requested value in some form of static variable. However, this variable still needs to be changed in value at least once, when the method is first called.
Can I do this inside the method getUserName()?
Furthermore, is this idea even possible within the bounds of OOP? Is it a similar concept to Prefetch?

It really looks to me that you need to access a field in a lazy way (i.e. only if needed, when needed). If so .NET has Lazy class for such cases which also provides thread safety out of the box:
public static Lazy<string> Name { get; } = new Lazy<string>(() => ReadNameFromFile());
Lazy will also ensure that you only create value once (i.e. call initiailization method) and on later calls it will simply return already retrieved value.

Create a static class. Something like this:
public static class ClientConfig{
public static string Name{get;set;}
public static bool IsAdult{get;set;}
public static int Age{get;set;}
public static void Load(){
// load your values
// ClientConfig.Name = name from file etc.
}
public static void Save(string newName, int age, bool value){
// save your values to the config file
}
}
And call ClientConfig.Load() first time when your app starts, for example (or whenever you need to retrieve config data)

Related

Trouble understanding reference types / reference copying in Service Locator implementation

In implementing a Service Locator, I've come across something I'm confused about with regards to reference types.
In the code below, I have a static class ServiceLocator which exposes 2 static methods, GetService and ProvideService - get returns the current service, and provide takes a new service as an argument and assigns it to the current service variable. If the provided service is null, it assigns currentService to a static defaultService initialised at the start of the class declaration. Simple stuff:
public static class ServiceLocator {
private static readonly Service defaultService = new Service();
private static Service currentService = defaultService;
public static Service GetService() {
return currentService;
}
public static void ProvideService(Service service) {
currentService = service ?? defaultService;
}
}
What i'm confused about is this: I have a separate class which stores a reference to the currentService at the start of its class declaration in the variable named referenceToCurrentServiceAtStart. When I provide the service locator with a new Service instance to update the current service, referenceToCurrentServiceAtStart appears instead to maintain the reference to defaultService:
public class ClassThatUsesService {
private Service referenceToCurrentServiceAtStart = ServiceLocator.GetService();
private static ClassThatUsesService() {
ServiceLocator.ProvideService(new Service());
// this variable appears to still reference the defaultService
referenceToCurrentServiceAtStart != ServiceLocator.GetService()
}
}
So the references appear to follow this kind of chain:
referenceToCurrentServiceAtStart -> defaultService -> (Service in memory)
Which is understandable, since referenceToCurrentServiceAtStart simply copies the currentService reference. However, the behaviour I'm looking for/would like is for referenceToCurrentServiceAtStart to always reference whatever currentService references, so it's updated by Provide(). Something more akin to:
referenceToCurrentServiceAtStart -> currentService -> (Service> in memory)
So, is this behaviour possible? I'm really unsure of how I'd achieve this kind of reference behaviour. I'm new to C# so it's very possible there's some obvious language feature I'm clueless about. Any help would be greatly appreciated.
is this behaviour possible?
No, not as you've described it. As you're already aware, all you get is a copy of the original reference. Changing the original reference doesn't change the copy, any more than copying the value of an int variable to another would allow you to later change the original and have the copy change:
int original = 17;
int copy = original;
original = 19;
// "copy" is still 17, of course!
If you want to always have the current value of the reference in ServiceLocator, then you should just always retrieve the value from that class, rather than using a local field. In your above example, you might indirect through a property, e.g.:
public class ClassThatUsesService {
private Service referenceToCurrentServiceAtStart => ServiceLocator.GetService();
}
It's a one character change (the = becomes =>), but don't be fooled. It's a significant change in implementation. What you wind up with instead of a field, is a read-only property (i.e. has only a get method and no set method), where that property's get method calls the ServiceLocator.GetService() method and returns the result.
Personally, I wouldn't bother. Unless you have some very strong expectation that the implementation of referenceToCurrentServiceAtStart will change in the future, you should just call ServiceLocator.GetService() directly. Don't even have the referenceToCurrentServiceAtStart property. Since the code expects to always get the current value, the best way to ensure that is to just always get the current value, straight from the class where that value is stored.
Finally, I'll take the opportunity to show a scenario that is similar to what you're asking, but not exactly. In particular, because you're trying to store the reference in a class field, the above is how you need to do it. But, the latest C# has "reference return values", which must be stored in "ref locals". Since you want to reference a static field, which is guaranteed to always exist, you can in fact return a reference to the field, store that in a local, and when you retrieve the local variable's value, it will always have whatever is in the field, because it's a reference to the field, not a copy of it.
You can see the example in the documentation (see links above), but here's another example that is more similar to what you're doing:
class Program
{
static void Main(string[] args)
{
// stores a reference to the value returned by M1(), which is to say,
// a reference to the B._o field.
ref A a1 = ref B.M1();
// Keep the original value, and create a new A instance
A original = a1, a2 = new A();
// Update the B._o field to the new A instance
B.M2(a2);
// Check the current state
Console.WriteLine($"original.ID: {original.ID}");
Console.WriteLine($"a1.ID: {a1.ID}");
Console.WriteLine($"a2.ID: {a2.ID}");
}
}
class A
{
private static int _id;
public int ID { get; }
public A()
{
ID = ++_id;
}
}
class B
{
private static A _o = new A();
public static ref A M1()
{
// returns a _reference_ to the _o field, rather than a copy of its value
return ref _o;
}
public static void M2(A o)
{
_o = o;
}
}
When you run the above, you'll get this output:
original.ID: 1
a1.ID: 2
a2.ID: 2
In other words, the variable a1 winds up yielding the same value found in a2, which is the new object passed to the B.M2() method to modify the B._o field, while the original copy of the B._o field value remains a reference to the original object that field referenced.
This doesn't work in your case, because the ref value that's returned has to be stored in a ref local. You can't put it into a class field. But it's similar enough to your scenario that I wanted to mention it, in case you want to change your design to allow that, or want to use that technique in some other scenario that does work in that way.

c# object by name in static method

My question is: Can I define a static method "meth1" in a static class "classB" that, when called from "classA", searches for a specific field (in "classA", not in the class in which is defined)?
I try to explain better: I need to do something like this:
public class classA
{
string someText;
int anInt;
bool trueOrFalse;
public classA()
{
...
...
var variable = classB.meth1("variableName");
...
...
}
}
public static classB
{
public static object meth1(string name)
{
...
... //use "name" to find the variable with that name in the class from which "meth1" is called.
...
}
}
That because I have to read a backup of "last run values" of variables contained in a .txt file, written line by line as "variable name = value".
So I read the .txt, create an hashtable "backupHashtable" which contains ("variable name";"value"), and then I want to search variables by string "variable name" and reset them to "value".
If someone of you knows a better procedure I'm listening. Maybe the use of a Dictionary?
Thank you!
UPDATING
Ok, now I have a clearer idea of what I want to do: I want to implement a class "ClassB", separate from my main class "classA". In this new class I would have a "meth1" method which, running in a separate thread, saves every 10 seconds (for example) the state of some variables belonging to "classA". To communicate the "meth1" what are the variables that he has to save, I want to use a list containing the names (in the format "string", that's what I thought, but I guess it's not the only way) of these variables.
If you're wondering why I want to do this in a separate thread the answer is this: my application performs some recognition operation of some objects in live stream images from multiple cameras and then ancillary operations must be isolated as much as possible from the main code to increase the speed of execution.
Now, perhaps, it is more understandable what I said before.
Yes, but you also need to pass a reference to the instance of A. Then use reflection to get or set the property.
public static void Meth1(object obj, string propertyName)
{
var prop = obj.GetType().GetProperty(propertyName);
var value = prop.GetValue(obj);
...
}
If I were to get values from a textfile into a class, I think I'd load them in a dictionary first, and then set all properties one by one. (Maybe unless there are, say, hundreds of properties). When using reflection, there is a chance that the textfile contains the name of a property you don't want to be changed from outside.
object value;
if (dict.TryGetValue("someProperty", out value)) { a.SomeProperty = value; }

Accessing Private Property value in C# 6.0 without creating it

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.

Datastructure to represent extensible and unique values

I've a small problem. I've a application monitoring part in a framework which is used by multiple applications.
Right now I've a functionality like this:
public enum Vars
{
CPU,
RAM
}
public void Add(Vars variable, object value)
{
[...]
}
The Variable which is used as Parameter in the Add method will be used as the name of the entry in the database.
Now I got the requirement, that applications can specify own variables outside the framework. Because you can't inherit from an enum this causes some trouble.
I see basicly 2 possibilities (which are bot not very satisfying in my opinion) to solve this.
Possibility 1:
public void Add(enum variable, object value)
This method would accept all sorts of enums, so users could use the Vars enums as well as enums which they've defined by themself. The problem with this solution: It would be possible, that users use the same names in both.. application and framework. I'm not able to differ between two enums with the value "CPU" (Framework may store percent values as "CPU", application may store process cpu usage as "CPU").
Possibility 2:
The second method would be an class instead a enum, something like:
public class Vars
{
public const string CPU = "CPU";
public const string RAM = "RAM";
}
The drawbacks here:
1. More to write.
2. I would have to define parameters as strings:
public void Add(string variable, object value);
This could lead to missuse as well (Applications which add strings directly instead defining a class which inherits from Vars).
Any thoughts on how to define a model which:
Can be inherited (to extend the values by applicationspecific values)
Can be used as a parameter
Ensures, that there are no double (=same value) entries
?
The context is not completely clear, but what about creating a class
public class Vars
{
public static Vars CPU = Vars.Get("CPU", 1);
public static Vars RAM = Vars.Get("RAM", 2);
//You can keep one of the params, name or id
private Vars(string name, int id)
{
...
}
public static Vars Get(string name, int id)
{
//check if id or name exists in static dictionary, and return that instance or create new one
}
}
public void Add(Vars variable, object value);
Now user can create any kind of Parameter and pass to the method,
Vars newVar = Vars.Get("MyNewParam", 10);
You can easily check if the passed param is one, about which you know
Get method returns same instance if the params are the same

Exposing common values from a custom structure/type

One of my projects has a value type/struct that represents a custom identifier string for a video format. In this case, it's going to contain a content type string, but that can vary.
I've used a struct so it can be strongly type when it's passed around, and perform some sanity checks on the initial string value.
public struct VideoFormat {
private string contentType;
public VideoFormat(string contentType) {
this.contentType = contentType;
}
public string ContentType {
get { return this.contentType; }
}
public override string ToString() {
return this.contentType;
}
// various static methods for implicit conversion to/from strings, and comparisons
}
As there are a few very common formats, I've exposed these as static read only fields with default values.
public static readonly VideoFormat Unknown = new VideoFormat(string.Empty);
public static readonly VideoFormat JPEG = new VideoFormat("image/jpeg");
public static readonly VideoFormat H264 = new VideoFormat("video/h264");
Is it better to expose the common values as static read only fields or as get only properties? what if I want to change them later? I see both methods used throughout the .Net framework, e.g. System.Drawing.Color uses static readonly properties while System.String has a static read only field for String.Empty, and System.Int32 has a const for MinValue.
(Mostly copied from this question but with a more specific and not directly related question.)
Properties are a good idea unless you are declaring something that never changes.
With properties you can change the inside implementation without affecting programs consuming your library and handle changes / variations. Consuming programs wont break and wont require to be recompiled.
e.g. (I know this is a bad example but you get the idea..)
public static VideoFormat H264Format
{
get{
// This if statement can be added in the future without breaking other programs.
if(SupportsNewerFormat)
return VideoFormat.H265;
return VideoFormat.H264;
}
}
Also keep in mind that if you decided to change a field to a property in the future, consuming code breaks.

Categories