[IronPython] C# Extension Methods and IP B2

Srivatsn Narayanan srivatsn at microsoft.com
Wed Apr 9 00:23:19 CEST 2008

Currently, it doesn't "just work". You will have to decorate your POCOExt with an ExtensionType attribute so:

[assembly: ExtensionType(typeof(POCO), typeof(POCOExt))]

Then from somewhere (python/c#) make this call:

This goes through the assembly and loads up everything in POCOExt into POCO.

-----Original Message-----
From: users-bounces at lists.ironpython.com [mailto:users-bounces at lists.ironpython.com] On Behalf Of Ben Hall
Sent: Tuesday, April 08, 2008 2:53 PM
To: Discussion of IronPython
Subject: [IronPython] C# Extension Methods and IP B2

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

My C# code is this:
    public static class POCOExt
        public static void Print(this POCO poco)
    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
>>> POCOExt.Print(p)
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?


Users mailing list
Users at lists.ironpython.com

More information about the Ironpython-users mailing list