.NET Extension methods from C++

Extension methods are a nice little feature now available in C# and VB.NET. They allow you to tack on new methods to existing classes for which you don’t own the original code. Now C++ does not support this natively and so I recently got bit when I was translating some C# code into C++ CLI.

While C# gave me nice Intellisense


C++ did not


The method I was calling on the NetworkCredential class did not exist in C++, only in C#. Intellisense had failed me!

The answer was simple once I realized that this was actually an extension method and how they are implemented. They are static methods on a different class which C# hooks up for you automagically. In C++ we need to call it directly, and pass in the “this” reference as the first parameter.

So a quick search in reflector or the online help turned up the actual class that implements GetWindowsAuthenticationToken(). It is WindowsLiveIdentityExtension.


And voila! working code again.