[IronPython] Passing arguments to C#

Dino Viehland dinov at microsoft.com
Tue Jan 4 20:29:57 CET 2011

Mark wrote:
> I had tried the IList<double>, and it works fine if I send in a list that is full of
> doubles, Using something like mylist = map(float,range(10))
> That was an awkwardness I wanted to avoid.  I wanted to be able to pass in
> mylist = range(10) just as easily.
> My C# routine will accept the argument as an IList (no type), but I'm unable
> to cast it afterwards.
> I finally solved the problem by accepting an IList, copying it element my
> element to a new list of the correct type. If a typecast is required, I assign it
> to a temporary variable of the same type first, then cast the temporary
> variable.
> This is the function I use for my conversion of each element.  I settled on
> using the IronPython.Runtime.List instead of IList because that's what I'm
> really passing in, but they seem to act exactly the same in this context.
>         static private double pToDouble(IronPython.Runtime.List pList, int index)
>         {
>             string type = pList[index].GetType().FullName;
>             if (type == "System.Int32")
>             {
>                 int tmp = (int)pList[index];
>                 return (double)tmp;
>             }
>             else if (type == "System.Double")
>             {
>                 return (double)pList[index];
>             }
>             else
>                 throw (new ApplicationException("Can't convert Python list to
> Double"));
>         }
> It's a little clumsy, but I'd rather push this down into the C# where I can hide
> it from my Python users.

I'd suggest Converter.ConvertToDouble(...) instead of doing the type checks
yourself (Converter is in IronPython.Runtime).  That'll work on anything the user
can throw at you and it'll use call site caching as well.  At the very least I'd suggest:

if(pList[index] is int) {
}else if(pList[index] is double) {

Which will be much, much more efficient and is a little easier on the eyes too.

More information about the Ironpython-users mailing list