The following question and answer addresses the use of an out parameter in a delegate:
I need to take this a step further. I have several conversion methods (functions), where I would like to utilize a delegate. For example, lets start with the below sample methods:
private bool ConvertToInt(string s, out int value)
{
try
{
value = Int32.Parse(s);
return true;
}
catch (Exception ex)
{
// log error
value = 0;
}
return false;
}
private bool ConvertToBool(string s, out bool value)
{
try
{
value = Convert.ToBoolean(s);
return true;
}
catch (Exception ex)
{
// log error
value = false;
}
return false;
}
I then declared the following delegate:
delegate V ConvertFunc<T, U, V>(T input, out U output);
What I would like to do is something like this (pseudo code):
if (do int conversion)
func = ConvertToInt;
else if (do boolean conversion)
func = ConvertToBool;
else ...
The compiler only lets me explicitly declare the delegate identifiers as follows:
ConvertFunc<string, int, bool> func1 = ConvertToInt;
ConvertFunc<string, bool, bool> func2 = ConvertToBool;
How can I declare a single identifier, to which I can assign any of a number of methods that follow the above pattern (based on the type of conversion I wish to perform)?
Update:
Assuming a dictionary containing string/object value pairs of:
private Dictionary<string, object> dict = new Dictionary<string, object>();
With values, such as:
this.dict.Add("num", 1);
this.dict.Add("bool", true);
Based on the answer, I was able to implement my delegate as follows:
public T GetProperty<T>(string key)
{
ConvertFunc<string, T, bool> func = ConvertToT<T>;
object val = this.dict[key];
T result;
if (func(key, out result))
return result;
else
return default(T);
}