[IronPython] C# Extension Methods and IP B2

Dino Viehland dinov at exchange.microsoft.com
Wed Apr 9 03:34:24 CEST 2008

We don't yet really support extension methods except for the ones provided by a host using the DLR style extension methods.

If you want to use those you need to just add:

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

And then call RuntimeHelpers.RegisterAssembly and pass in the declaring assembly.  We should pick up the types after that.

RuntimeHelpers.RegisterAssembly is not final API.  It's likely to change in B2 as one of the last bug fixes to multi-runtime support.  I don't know that we will support the C# 3.0 style extension attributes in the 2.0 timeframe.  While we could presumably support it we'd be required to create every custom attribute on the 1st parameter of every method in an assembly.  Therefore it may be more significant of a feature than we'd like to fit in during the betas because we'd have to do something more intelligent than that.  Hopefully this work around will suffice - at least for your own extension types.

And FYI I'm guessing you're probably using 2.0 B1 not B2 :).

-----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