21

In C#, extension methods can be created by

public static class MyExtensions {
    public static ReturnType MyExt(this ExtType ext) {
        ...
    }
}

Since all of my library are written in C++/CLI, I would like to create the .net extension methods also in C++/CLI (in order to have one DLL instead of two). I've tried the following code

static public ref class MyExtensions {
public:
    static ReturnType^ MyExt(this ExtType ^ext) {
        ...
    }
};

But the compiler can not recognize keyword 'this' in the first argument.

error C2059: syntax error: 'this'

Is there some way to create the extension method in C++/CLI ?

KiKi
  • 505
  • 1
  • 4
  • 12

1 Answers1

46

You just have to decorate the method and the containing class with ExtensionAttribute:

using namespace System::Runtime::CompilerServices;
...

[ExtensionAttribute]
public ref class MyExtensions abstract sealed {
    public:        
        [ExtensionAttribute]
        static ReturnType MyExt(ExtType ^ext) {
            ...
        }
};
  • 14
    Thank you for providing the namespace too - so many times people (who are otherwise being helpful) miss this. – philsquared Aug 13 '12 at 08:12
  • 3
    You should also mark the assembly with [assembly: ExtensionAttribute]. Personally I would add this to AssemblyInfo.cpp. – Bert Huijben Mar 12 '18 at 13:55