views:

527

answers:

3

I'm writing a .NET assembly in C++/CLI to be used in our C#-based application. I'd like the application to see some of the C++ methods as extension methods. Is there some attribute I can apply to the declaration to specify that a method should be seen as an extension method from C#?

A: 

I don't think you can. Extension methods are merely syntactic sugar, converted to static methods by the compiler.

Aistina
so my question is, how do I add the right syntactic sugar?
Simon
+1  A: 

Make it a static method in a non-nested, non-generic static class, with the Extension attribute applied to both the class and the method.

The tricky bit here may be the concept of a static class - that may not exist in C++/CLI... I'm not sure. It's possible that the C# compiler doesn't really care whether or not the class is static when detecting an extension method, only when declaring one. It's certainly worth a try without it.

Jon Skeet
@Downvoter: Care to explain?
Jon Skeet
+2  A: 

I had the same problem and here is a little example of an extension method in C++/CLI:

using namespace System;

namespace CPPLib 
{
    [System::Runtime::CompilerServices::Extension]
    public ref class StringExtensions abstract sealed
    {
    public: 
        [System::Runtime::CompilerServices::Extension]
        static bool MyIsNullOrEmpty(String^ s)
        {
            return String::IsNullOrEmpty(s);
        }
    };
}

This extension method can be used just like any other in C#:

using CPPLib;

namespace CShartClient
{
    class Program
    {
        static void Main( string[] args )
        {

            string a = null;
            Console.WriteLine( a.MyIsNullOrEmpty() ? "Null Or Empty" : "Not empty" );
            a = "Test";
            Console.WriteLine( a.MyIsNullOrEmpty() ? "Null Or Empty" : "Not empty" );
            Console.ReadKey();
        }
    }
}

Unfortunately it seems C++ does not provide us with the "syntactic sugar" like in C#. At least I did not find it.

rotti2