[IronPython] C# Extension Methods and IP B2

Ben Hall ben2004uk at googlemail.com
Tue Apr 8 23:52:41 CEST 2008


Hi everyone,

Tonight I was going to write a blog post on C# Interop so I I was
playing around a bit more with some of the new C# 3.0 features and I
looked at Extension methods and I can't seem to get it to work with IP
B2.

My C# code is this:
    public static class POCOExt
    {
        public static void Print(this POCO poco)
        {
            Console.WriteLine(poco);
            Console.WriteLine(poco.Created);
        }
    }
    public class POCO
    {
        public DateTime Created { get; set; }

        public POCO()
        {
            Created = DateTime.Now;
        }
    }

I drop that assembly into my DLLs folder, when using it in ipy it
doesn't seem to be detecting the extension methods.  After doing a dir
on POCO, I expected to see the method Print.

>>> from DLRInterop import *
>>> p = POCO()
>>> dir (p)
['Created', 'Equals', 'Finalize', 'GetHashCode', 'GetType',
'MemberwiseClone', 'ReferenceEquals', 'ToString', '__class__',
'__delattr__', '__doc__', '__getattribute__', '__hash__', '__init__',
'__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__',
'__str__', 'get_Created', 'set_Created']
>>> p.Print()
Traceback (most recent call last):
  File , line unknown, in Initialize##48
AttributeError: 'POCO' object has no attribute 'Print'

This appeared to work, but it does go against C# 3.0 and isn't a great
approach....
>>> POCOExt.Print(p)
DLRInterop.POCO
08/04/2008 22:43:59

Is there anything special I need to do to get this to work as I would
expect, or is there something where to call the Extension Method you
need to go to the extension class?

Cheers

Ben
Blog.BenHall.me.uk



More information about the Ironpython-users mailing list