I have created a dictionary as seen in the code below. It's been the only way I've found to get the value of the variable "myCondition" to be updated inside the Tvalue field of the dictionary.
public class MyClass
{
delegate bool Delegate();
Dictionary<string, Delegate> map;
bool myCondition;
public MyClass()
{
map = new Dictionary<string, Delegate>();
map.Add("key", MyDelegate);
}
public bool MyDelegate()
{
return myCondition;
}
}
I would like to be able to dispense with the function MyDelegate()
and put the variable " myCondition " directly in the dictionary... Basically what I want is to pass a pointer to that variable, but from what I have seen in C# pointers are almost "prohibited" .
I have thought that perhaps some kind of casting can be done and convert that variable into a function and thus pass it through a delegate... something like the following code:
public class MyClass
{
delegate bool Delegate();
Dictionary<string, Delegate> map;
public MyClass()
{
map = new Dictionary<string, Delegate>();
bool myCondition;
public MyClass()
{
map.Add("key", (Delegate)myCondition);
map.Add("key", (Func)myCondition);
}
}
Is there any way to do something like that? How would it be done?
Thank you!!
I don't really understand what you mean by converting the variable to a function , something that I don't think is possible. What you can do is omit the variable and define a function (
Func
) that calculates the value to return.I give you an example. First we define the dictionary, with the
TValue
aFunc<bool>
:Later, we simply add a dictionary entry defining what we should return, in this case
myCondition
:Finally, we can query it by calling the function returned by the dictionary:
As an additional data, you could perfectly calculate the value defining
Func
so that it can accept input values: