Cedric Raymond Cedric Raymond - 2 months ago 11
C# Question

How to pass params object[i] to a template function in C#

I am trying to send a params object[i] to a T function but I cant find the right syntax.

Here is an example to show the context of what I am trying to achieve:

private bool decodeValue<T>(int id,ref T item, string code)
{

if(!TypeDescriptor.GetConverter (item).CanConvertFrom(typeof(string)))
{
errorThrow (id + 2);
return false;
}

try
{
item = ((T)TypeDescriptor.GetConverter (item).ConvertFromString (code));
}
catch
{
errorThrow (id + 2);
//item = default(T);
return false;
}

return true;
}

private bool decodeValues(string[] code, int id, params object[] items)
{
for (int i = 0; i < items.Length; i++)
{
System.Type t = items [i].GetType();
//in this part i cant find the correct syntax
if(decodeValue<(t)items[i]>(id, ref items[i] as t, code[i+2]))
{

}
}

return false;
}


At the line
decodeValue<(t)items[i]>(id, ref items[i] as t, code[i+2]

no matter what syntax I try, the compiler tells me that after
>
it expects a
)


I could inline the function decodeValue into the for loop but I think there is a more elegant way of doing it. Any suggestions?

Answer

In your example, you replace content of items. Why do even need templated function? Just do this:

private bool decodeValue(int id,ref object item, string code)
{

    if(!TypeDescriptor.GetConverter(item).CanConvertFrom(typeof(string)))
    {
        errorThrow (id + 2);
        return false;
    }
    try
    {
        item = TypeDescriptor.GetConverter(item).ConvertFromString(code);
    }
    catch 
    {
        errorThrow (id + 2);
        return false;
    }

    return true;
}

private bool decodeValues(string[] code, int id, params object[] items)
{
    for (int i = 0; i < items.Length; i++) 
    {
        //in this part i cant find the correct syntax
        if(decodeValue(id, ref items[i], code[i+2]))
        {

        }
    }

    return false;
}

If you ever need type of item in your code, just call .GetType() where it actualy needed. That is not only good way to do things, but in some cases performance effective (compiler can greatly optimise some calls of this function).

Comments