4

The following question and answer addresses the use of an out parameter in a delegate:

Func<T> with out parameter

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);
}
Community
  • 1
  • 1
Elan
  • 6,084
  • 12
  • 64
  • 84
  • 3
    It's hard to advise you on how to proceed without seeing the rest of the method which would *call* this delegate. I suspect you'll find that when you try to turn the pseudo-code into real code, the reasons behind the compiler error become clearer. – Jon Skeet Nov 23 '11 at 21:44

1 Answers1

6

I think you're looking for something like

private bool ConvertToT<T>(string s, out T value)
{
    try
    {
        value = (T)Convert.ChangeType(s, typeof(T));

        return true;
    }
    catch (Exception ex)
    {
        // log error // not sure what you're trying here?
        value = default(T);
    }
    return false;
}
Ron Sijm
  • 8,490
  • 2
  • 31
  • 48