How to handle unassigned properties when using Singleton Pattern - c#

I have created the following class based on a Singleton Pattern:
public sealed class UTrans
{
private static volatile UTrans _instance;
private static readonly object syncRoot = new Object();
private UTrans(){}
private static UTrans Instance
{
get
{
if (_instance == null)
{
lock (syncRoot)
{
if (_instance == null)
_instance = new UTrans();
}
}
return _instance;
}
}
}
Within this Class I have created an enum property and string property
private static MethodType _method; // Alphabectic 1 - 50
public static MethodType Method
{
get { return _method; }
set { _method = value; }
}
private static string _uName;
public static string UserName
{
get { return _uName; }
set { _uName = value; }
}
I also have some methods that take a number of arguments in this class. When I call the class instance in code, if the user assigns values to the properties; those values will be used. Otherwise, the values passed as arguments will be used.
This works fine in the case of the UserName property by checking for a null value on the property:
var un = UserName ?? user;
However I cannot perform the same check for the enumeration property because it seems that the property automatically assumes the 1st value of the enumeration if one is not assigned.
I tried to circumvent the issue by assigning the 1st value of the enum as "Unspecified". Then I may proceed to code as such:
var processMethod = TranslateMethodType(Method) == "Unspecified" ? method : Method;
Where TranslateMethodType is a private method that converts the selected enumeration to a equivalent string value.
I don't believe this is the most elegant approach to the issue though and would like some feedback on possible alternatives to this issue.
Is there a way to check that a value has not been set for the MethodType property by the user of the class without having to add an "Unspecified" value as the first value since this value is ONLY there as a way to indicate no value was set?
Obviously, this may not be the case if the user decides to use the value and it would yield undesirable results to construct the code this way.
Can a enumeration Method be marked as nullable???

Can a enumeration Method be marked as nullable???
Yes.
public Nullable<MyEnum> Bob(){
//stuff
}
var bob = Bob() ?? MyEnum.Default;

Yes, you can make the Method field/property nullable.
private static MethodType? _method; // Alphabectic 1 - 50
public static MethodType? Method
{
get { return _method; }
set { _method = value; }
}
Then you can do
var processMethod = Method == null ? method : Method.Value;
or
var processMethod = Method.HasValue ? Method.Value: method;

You can mark it as nullable however what you're experiencing is expected behaviour.
Value types that are members of a reference type are initialized to 0. This is why you should always provide a value of 0 for your enums. If you don't, then users of your class will never know that the class has invalid state.

Related

Single instance of a helper object with parameters

One of our projects makes use of key-value pairs where certain runtime parameters - that do not change per instance of the program - determine the value gotten. For example:
Program run in test mode with the parameter "Municipal":
Key: "testMunicipalDirectory"
Value: "C:\Foo\Bar\"
Program run with the parameter "State":
Key: "StateDirectory"
Value: "C:\Bar\Baz\"
To make it slightly more complicated, if there is no matching key for, say "testMunicipalImagesDirectory", there is a fallback of "defaultImagesDirectory":
Key: "testMunicipalImagesDirectory" ?? "defaultImagesDirectory"
Value: "C:\Foo\Bar\Images" ?? "C:\Images"
Currently, there's a lot of code duplication/inefficiencies, and room for error. Every time one of these is referenced there's string concatenation and null-coalescing and other stuff going on.
It seems like this would benefit from a single-instance object that is passed certain parameters on initialization (test or not, "State" or "Municipal", etc), that will return the correct values for each different property the keys represent.
Many answers I found to questions asking how to use the singleton design pattern with parameters basically boil down to "if it uses parameters, you probably do not want a singleton". In my case, it is invalid to attempt to initialize the object with different values, and an exception should be thrown if this happens.
This is how I would accomplish this goal (pseudo-C#) (lazy-loading is not a requirement but is used here):
public sealed class Helper
{
// how can we enforce that Init has been called?
private static readonly Lazy<Helper> lazyLoader = new Lazy<Helper>(() => new Helper(name, test));
public static Helper Instance { get { return lazyLoader.Value; } }
public static void Init(string name, bool test)
{
// if it has already been initalized
throw new InvalidOperationException("This has already been initalized.");
// else initalize it
}
private string Name { get; set; }
private bool Test { get; set; }
private Helper(string name, bool test) { } // assign to properties, any other ctor logic
public string Directory
{ get { return ValueGetter.Get((this.Test ? "test" : "") + this.Name + "Directory"); } }
}
public static class ValueGetter
{
public static string Get(string key, string fallbackKey)
{
if (Keys.Any(k => k == key))
return Keys[key].Value;
else
return Keys[fallbackKey].Value;
}
}
But as you can see, there are questions remaining. How can it enforce calling Init before using the Instance, but not require those parameters to be passed every time Instance is accessed?
Is this the correct direction to go, or is there a better design pattern to use?

Load property lazy loading

I have a property which getter should load its value only the first time. The second time it returns the loaded value without loading it again:
private Object _MemberValue;
public Object MemberValue
{
get
{
if(_MemberValue == null)
{
_MemberValue = LoadMember();
}
return _MemberValue;
}
}
In VB.NET there is the Static keyword. With it you don't have to declare a class wide member.
Public Property MemberValue as Object
Get
Static value as Object = Nothing
If (value is Nothing) Then
value = LoadMember()
End If
Return value
End Get
End Property
In C# there isn't such a keyword.
Are there better C# implementations of this problem or other patterns?
Are there better C# implementations of this problem or other patterns?
Probably not. You can use Lazy<T> as an replacement if you like, but basically it is the same as your first example. Using Static in VB.NET has some serious drawbacks, so I wouldn't use it either way.
If you prefer Lazy<T>, this is what I would use:
private Lazy<object> _MemberLazy = new Lazy<object>(LoadMember);
public object MemberValue
{
get
{
return _MemberLazy.Value;
}
}
Your initial approach seems appropriate, I have never had reason to do something different. That said if your goal here is to avoid a class level field that could potentially be written to outside the getter, perhaps something like this would work. There are a number of other ReadOnly, WriteOnce, SetOnce implementations that would also work similarly.
ReadOnlyField.cs
public class ReadOnlyField<T>
{
private bool _frozen;
private T _value;
public T Value
{
get { return _value; }
set
{
if (_frozen)
throw new InvalidOperationException();
_value = value;
}
}
public void Freeze()
{
_frozen = true;
}
}
YourObject.cs
public class YourObject
{
private readonly ReadOnlyField<object> _someMember;
public object MemberValue
{
get
{
if(_someMember.Value == null)
{
_someMember.Value = LoadMember();
_someMember.Freeze();
}
return _someMember.Value;
}
}
public YourObject()
{
_someMember = new ReadOnlyField<object>();
}
}
It's not perfect. Unlike your VB.Net example; code outside of the getter could write to the field first, but at least you're protected from it being overwritten after Freeze is called.

How to get Getter backing field from PropertyInfo?

I have a class as follows:
class Foo : PropertyChangedBase {
private int _property;
public int Property {
get { return _property; }
set { OnAssignPropertyChanged("Property", () => _property, value); }
}
PropertyChangedBase implements INotifyPropertyChanged with the following methods:
protected void OnAssignmentPropertyChanged<T>(string propertyName, Expression<Func<T>> fieldExpression, T value)
{
var get = fieldExpression.Compile();
if (get().Equals(value))
{
return;
}
// invoke set property method
SetProperty(fieldExpression, value);
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
}
private void SetProperty<T>(Expression<Func<T>> fieldExpression, T value)
{
if (fieldExpression == null)
{
throw new ArgumentNullException(nameof(fieldExpression));
}
var memberExpression = fieldExpression.Body as MemberExpression;
if (memberExpression == null)
{
throw new ArgumentException("fieldExpression");
}
var field = memberExpression.Member as FieldInfo;
if (field == null)
{
throw new ArgumentException("fieldExpression");
}
field.SetValue(this, value);
}
I would prefer to call:
OnAssignPropertyChanged(() => Property, value);
The only way this will work is if I can get the backing field for the property getter and then pass that to SetProperty. Is it possible to get the FieldInfo or target member from the property get method?
As a general answer, yes you can do, at least under controlled conditions. But the only case you should do this is when you are absoluty sure what you are doing and only with limited support, because there will be cases you can not handle.
Have a look at the answer here: Find all property references using reflection. The target is a bit different but the approach is similar for finding field references. Since the answer there already includes the necessary code i will just outline the way to go:
All metadata items in .Net are referenced by tokens. To get tokens used inside a method you have to parse the MethodBody (by skipping all the things you wont inspect) and then resolve the found tokens in their module. Remember to use the BitConverter when reading the tokens from the stream to resolve them.
But now to the down side; the only time you can really safely use this to find the backing fields of a properties getter, is when you find a simple get method, with a well defined opcode sequence like Ldfld, Ret or something like that. Maybe you can define a few patterns that the C# compiler will emit for simple and autoimplemented properties. If you find anything different there is no other way as to resign and throw an exception, because the getter could contain any code.
Like always with reflection, only use whitelist approaches, check for the conditions you expect and throw exeptions in any other case or you will run into a NullReferenceException sooner or later.
If this is worth the trouble is for you to decide, but in general you could do this since .Net 2.0 and do not even need a fancy external lib.
No, in general case you can't. Just compare two classes:
public class Test {
private int _propA;
private int _propB;
public int PropA {get { return _propA; }}
public int PropB {get { return _propB; }}
}
public class TestSwapped {
private int _propA;
private int _propB;
// please, notice swapped backing fields
public int PropA {get { return _propB; }}
public int PropB {get { return _propA; }}
}
you'll get identical PropertyInfo[] and FieldInfo[] arrays but different backing fields
In pursuing this for a different question, here is an extension method for the simple cases - an autogenerated backing field, or a get that just returns a backing field:
public static class MethodInfoExt {
const int IL_ldarg0 = 0x02;
const int IL_ldfld = 0x7B;
public static FieldInfo FieldInfoFromGetAccessor(this MethodInfo getAccessorMI) {
var body = getAccessorMI.GetMethodBody().GetILAsByteArray();
if (body[0] == IL_ldarg0 && body[1] == IL_ldfld) {
var fieldToken = BitConverter.ToInt32(body, 2);
return getAccessorMI.DeclaringType.Module.ResolveField(fieldToken);
}
else
return default;
}
}
You can not. Property can have no backing fields or sets of backing fields.
Even set property can have no backing fields at all.
public Int32 Prop
{
set { Debug.WriteLine(value.ToString()); }
get { return 1; }
}
What are you expecting to get in FieldInfo?
Property is just a syntax sugar for a pair of set/get methods, or mutators. Being a method allows them to contain as much code as needed, including being just empty and, of course, there is no requirement to have a backing field from compiler perspective.

Pointing variables at other variables in c#

Is it possible to have one variable point to another variable for shortcut purposes? For instance, let's say I have a variable in one class that is called SharedResources.proxTelescope, how do I get a variable in another class called prox to point to the first variable, in a sort of shortcut type of thing. I could just do var prox = SharedResources.proxTelescope;, but if proxTelescope changes, it won't reflect on prox, will it? How should I do it instead.
I would set things up as a property.
private <type> prox
{
get { return SharedResources.proxTelescope; }
set { SharedResources.proxTelescope = value }
}
You can create a property, something like:
public YourTypeHere prox
{
get { return SharedResources.proxTelescope; }
set { SharedResources.proxTelescope = value; }
}
If the variables are classes then they are reference type, so any change in one of them will be reflected in the other.
If the variables are structs, then they are value types and you have a problem, you can make some function(or property) to get the value.
If the value should be 'shared' among all instances, then it would probably be best to have the variable exist as a static member of the class it is on, and create an instance property that retreives the value of the static variable.
Another approach would be to use a Func<T>:
public class MyClass
{
public Func<DesiredType> ValueGetter {get;set;}
public DesiredType Value { get { return ValueGetter(); } }
}
This can then by used this way:
var myClass = new MyClass();
myClass.ValueGetter = () => SharedResources.proxTelescope;
var value = myClass.Value;

Factor out a null check for a variable only set by one constructor

In the class below, only the second constructor takes a ForumThread object. Otherwise, it is set to null.
IncrementViewCount(), LockForumThread(), and other methods depend on _ft being non-null.
Without extracting the null check into a new private method, is there some simpler re-factoring I can do or a better design to guard against the use of the wrong constructor with those dependent methods?
private readonly IThread _forumLogic;
private readonly ForumThread _ft;
public ThreadLogic(IThread forumLogic)
: this(forumLogic, null)
{
}
public ThreadLogic(IThread forumLogic, ForumThread ft)
{
_forumLogic = forumLogic;
_ft = ft;
}
public void Create(ForumThread ft)
{
_forumLogic.SaveThread(ft);
}
public void IncrementViewCount()
{
if (_ft == null)
throw new NoNullAllowedException("_ft ForumThread is null; this must be set in the constructor");
lock (_ft)
{
_ft.ViewCount = _ft.ViewCount + 1;
_forumLogic.SaveThread(_ft);
}
}
public void LockForumThread()
{
if (_ft == null)
throw new NoNullAllowedException("_ft ForumThread is null; this must be set in the constructor");
_ft.ThreadLocked = true;
_forumLogic.SaveThread(_ft);
}
If you implement a property for the ForumThread then you could throw the exception from the get if it is null. This may create a method in the underlying IL but its not a new private method in your class (plus - whats wrong with having a new method?)
Why don't sub-class ThreadLogic and provide additional constructor and dependent methods only in the sub-class? Alternatively, if you already have some hierarchy, you can use delegation and decorator pattern to add new features. In both cases you can check null in single place: constructor

Categories