I have a lot of pieces of code which has to be run one time during initialization.
I have to use a boolean flag this way because it is in an event
bool _fuse;
void PerformLayout()
{
Size size;
if (!_fuse)
{
size = _InitialContainerSize;
_fuse = true;
}
else
size = parent.Size;
// ...
}
Because it happens often, I did something to make this boolean variable to look like a fuse :
So I did this:
bool _fuse;
void PerformLayout()
{
Size size;
if (!Burnt(ref _fuse))
size = _InitialContainerSize;
else
size = parent.Size;
// ...
}
If it is initialized to false, the result of the query returns false once, make the switch to true, and successive calls return true.
public static bool Burnt(ref bool value)
{
if (!value)
{
value = true;
return false;
}
else
return true;
}
Of course, it works, but I am only moderately satisfied and I am sure there is more elegant solutions. What would be yours ?
I think the general thrust in avoiding repetition here is right (even if the repetition is very small … but still). Just encapsulate it and name it properly:
struct InitializerGuard {
private bool hasRun;
public bool HasRun() {
if (hasRun)
return true;
hasRun = true;
return false;
}
}
Usage:
InitializerGuard sizeInitializer;
void PerformLayout()
{
Size size;
if (!sizeInitializer.HasRun())
size = _InitialContainerSize;
else
size = parent.Size;
// ...
}
But if you find yourself using this pattern very often this might indicate that a refactoring is in order. Maybe just assign default values to some variables? Why aren’t they initialised, anyway?
There are many ways of achieving this. You can create a complex state machine performing your logic (fastest) but for many cases, that will be overkill. Alternatively, you can keep track of an boolean which holds the state of your instance just like you have now. You can also decide to combine both solutions into a simple state machine with methods like (moderatly fast):
public class TestClass
{
private Action performLayoutAction;
public TestClass()
{
// initial state
performLayoutAction = InitializePeformLayout;
}
public void PerformLayout()
{
performLayoutAction();
}
private void InitializePeformLayout()
{
// whatever
performLayoutAction = ContiniousPerformLayout;
}
private void ContiniousPerformLayout()
{
// whatever
}
}
You can use nullable types and the null coalescing operator to declare a Size property:
Size? _containerSize;
Size ContainerSize {
get {
return (_containerSize ?? (_containerSize = _InitialContainerSize)).Value;
}
}
You can then use it like this:
void PerformLayout() {
var size = ContainerSize;
// ...
}
If the type you want to lazy initialize is a reference type it becomes even simpler.
Another option is to use the Lazy<T> type. This can used in multi-threading scenarios where the above code can break:
Lazy<Size> _containerSize = new Lazy<Size>(() => _InitialContainerSize);
void PerformLayout() {
var size = _containerSize.Value;
// ...
}
Related
Not exactly a big deal to do this one myself, but I am curious if C# gives this to me anywhere:
public static IEnumerable<bool> AllBools {
get {
yield return false;
yield return true;
}
}
Here's the code, a bit clunkier than you probably want, but it works:
public static IEnumerable<bool> BoolValues {
get {
return new bool[]{true, false};
}
}
Edit: if you want code to enumerate over all values of an enum (which would be a lot more useful, imo), here is also the code:
public enum TrueOrFalse
{
True,
False
}
public static IEnumerable<TrueOrFalse> BoolValues {
get {
List<TrueOrFalse> allValues = new List<TrueOrFalse>();
foreach (var value in Enum.GetValues(typeof(TrueOrFalse))){
allValues.Add((TrueOrFalse)(value));
}
return allValues.AsEnumerable();
}
}
Even simpler, as found here (How to get an array of all enum values in C#?):
List<TrueOrFalse> valuesAsList = Enum.GetValues(typeof(TrueOrFalse)).Cast<TrueOrFalse>().ToList();
Suppose I have a C# class that has multiple properties that all look like this:
private bool _var1Dirty = true;
private Double? _var1;
public Double? Var1
{
get
{
if (_var1Dirty)
{
_var1 = Method_Var1();
_var1Dirty = false;
}
return _var1;
}
}
And the only differences between each of these properties would be:
The type of return var (in this case Double?, but could just as easily be int, string, etc)
The method call - Method_Var1() (Each property would have a different one)
Is there any way I could write this as a custom class?
Something along the lines of:
public class Prop
{
public delegate T Func();
private bool _dirty = true;
private T _val;
public T Val
{
get
{
if (_dirty)
{
_val = Func;
_dirty = false;
}
return _val;
}
}
}
And then I could pass into it the:
Return type T
Method Func
(PS - I know this won't compile / is dead wrong, but I wanted to give an idea of what I'm looking for)
Any help / guidance would be really appreciated.
Thanks!!!
You're close. You can do something along the lines of this:
public class Dirty<T>
{
public Dirty(Func<T> valueFactory)
{
this.valueFactory = valueFactory;
dirty = true;
}
private Func<T> valueFactory;
private bool dirty;
private T value;
public T Value
{
get
{
if (dirty)
{
value = valueFactory();
dirty = false;
}
return value;
}
}
}
And you consume it like this:
Dirty<double?> dirtyDouble = new Dirty<double?>(() => SomethingThatReturnsADouble());
double? value = dirtyDouble.Value;
I'm not sure what the dirty checking actually does, but if you need someone more complicated than a bool you can always turn it into some Func<T> the checks for dirtiness.
Edit:
Given #mikez comment and your answer, you can save yourself the creation of the Dirty<T> class by using the built in Lazy<T>, which also guarantess thread safety:
public class F
{
private Lazy<double?> lazyDouble = new Lazy<double?>(() =>
MethodThatReturnsNullableDouble(), true);
public double? Value
{
get
{
return lazyDouble.Value;
}
}
}
I have a list of Func and I want to add elements.
If I add them on Start like below, no problem:
public List<System.Func<bool>> conditions = new List<System.Func<bool>>();
void Start()
{
conditions.Add(Iamdead);
conditions.Add(Iamalive);
}
bool Iamdead()
{
...
return ...;
}
bool Iamalive()
{
...
return ...;
}
But I want to define the list without Start so that I have a clean list of methods that I can see as elements in a row. I have tried the classic format:
public List<System.Func<bool>> conditions = new List<System.Func<bool>>()
{
bool Iamdead()
{
...
return ...;
}
,
bool Iamalive()
{
...
return ...;
}
};
This gave me parsing error
I tried like that:
public List<System.Func<bool>> conditions = new List<System.Func<bool>>()
{
Iamdead,Iamalive
};
static bool Iamdead()
{
...
return ...;
}
static bool Iamalive()
{
...
return ...;
}
This worked only if the methods are static but I do not want them to be static. Without static, it doesn't work. It seems I couldn't understand the data structure here. Can anyone tell me the correct way of defining Func in a list?
Thanks
I strongly suspect the problem is that you're trying to access this (implicitly) within a field initializer. You're not allowed to do that. Just move the initialization into a constructor:
// You don't really use public fields, do you?
private readonly List<Func<bool>> conditions;
public MyClass()
{
conditions = new List<Func<bool>> { Method1, Method2 };
}
private bool Method1() { ... }
private bool Method2() { ... }
(I'm assuming you actually want your conditions to depend on state within the instance. If they don't, you don't need this. If the methods aren't used other than for these conditions, and they're short enough, you might want to use lambda expressions instead.)
Like so:
public List<System.Func<bool>> conditions = new List<System.Func<bool>>()
{
() => false,
() => true,
};
You can just use lambdas:
public List<System.Func<bool>> conditions = new List<System.Func<bool>>()
{
() =>
{
return false;
}
,
() =>
{
return true;
}
};
I have a class that has two boolean properties - A,B.
I want to add a restriction such that A and B cannot be false at the same time.
Is there some attribute I can apply to the Class such that A=false and B = false becomes invalid?
There's nothing built in. You're going to need to write this logic yourself. There are three ways to do so, in declining order of "good practice":
Replace both with an enum: When you have two mutually exclusive states, you're better off combining them into a single value that has multiple states. If you really need them as separate booleans, you can write get-only properties which check the central state.
public enum MyState
{
NoState,
IsStateA,
IsStateB,
}
public MyState State { get; set; }
public bool IsStateA { get { return State == MyState.IsStateA; } }
public bool IsStateB { get { return State == MyState.IsStateB; } }
Enforce it in the business logic layer: In this case, you just enforce the restriction in the UI, or wherever the input is coming from. Whenever you try and toggle one, you check the state of the other and notify/alter appropriately.
Write setter logic to toggle the other: When one is set, set the other.
private bool _StateA;
private bool _StateB;
public bool IsStateA {
get { return _StateA; }
set {
_StateA = value;
if (value) _StateB = false; // If this is now true, falsify the other.
}
}
public bool IsStateB {
get { return _StateB; }
set {
_StateB = value;
if (value) _StateA = false; // If this is now true, falsify the other.
}
}
Choice #1 is really the best way to handle a "three state" situation like this, but the others will also work.
why not use simple get/set logic?
private bool a;
public bool A
{
get { return a; }
set
{
if (value == B)
{
throw new Exception("A and B have the same boolean value!");
}
else
a = value;
}
}
or allow A and B to be set in either state regardless but have a third boolean for storing logic validity:
public bool IsValid { get { return (A == B); } }
Long switch statments are often frowned upon. The solution is to use polymorphism. However what if the thing I'm switching on is not a type code? What I would like to do is replace the switch statement with something like this...
public void HandleString(string s = "Hello")
{
...
}
public void HandleString(string s = "Goodbye")
{
...
}
...
HandleString("Hello"); // results in the first method being called.
This would replace the following...
string s = "Hello";
switch(s)
{
case "Hello":
...
break;
case "Goodbye":
...
break;
default;
break;
}
Any ideas? In theory I think you could do away with 'if/switch' statements altogether and just call methods that are automatically bound based on the value of an expression.
If you have a large number of options, and high possibility that there will be more in the future - or you just need to system to be easily extensible - then you can always use an explicit dispatch table:
Dictionary<string, Action<string>> actions =
new Dictionary<string, Action<string>>()
{
{ "Hello", HandleHello },
{ "Goodbye", HandleGoodbye }
};
private static void HandleHello(string s) { ... }
private static void HandleGoodbye(string s) { ... }
...
actions[s](s);
You can also provide a way to extend the table by allowing external clients of your API to register their own handler for a given string.
There are languages that implement that sort of semantics. One that I'm familiar with is the compiler generator tool called Elegant from Phillips.
In a language like this, a simple factorial algorithm might look like:
fact (value : Int) : Int
conditions value < 0
{
{ "Illegal input value\n" } astype Message
return 0
}
fact (value = 0) : Int
{
return 0
}
fact (value = 1) : Int
{
return 1
}
fact (value : Int) : Int
{
return value * fact(value - 1);
}