Extension Methods in C++

What are Extension Methods?

Extension methods allow developers to add new methods to the public
contract of an existing CLR type,
without having to sub-class it or
recompile the original type.

Extension Methods help blend the
flexibility of "duck typing" support
popular within dynamic languages today
with the performance and compile-time
validation of strongly-typed
languages.

Reference: http://weblogs.asp.net/scottgu/archive/2007/03/13/new-orcas-language-feature-extension-methods.aspx

Here is a sample of an Extension Method (notice the this keyword infront of the first parameter):

public static bool IsValidEmailAddress(this string s)
{
Regex regex = new Regex(@"^[\w-\.]+@([\w-]+\.)+[\w-]{2,4}$");
return regex.IsMatch(s);
}

Now, the above method can be called directly from any string, like such:

bool isValid = "so@mmas.com".IsValidEmailAddress();

The added methods will then also appear in IntelliSense:

alt text
(source: scottgu.com)

As regards a practical use for Extension Methods, you might add new methods to a class without deriving a new class.

Take a look at the following example:

public class Extended {
public int Sum() {
return 7+3+2;
}
}

public static class Extending {
public static float Average(this Extended extnd) {
return extnd.Sum() / 3;
}
}

As you see, the class Extending is adding a method named average to class Extended. To get the average, you call average method, as it belongs to extended class:

Extended ex = new Extended();

Console.WriteLine(ex.average());

Reference: http://aspguy.wordpress.com/2008/07/03/a-practical-use-of-serialization-and-extension-methods-in-c-30/

Where is the proposal for standardization of extension methods in C++?

There is a proposal for Unified (var Uniform) Call Syntax for C++. From 10,000 feet PoV, it will allow extensions methods a la C# as well as really blending the difference between method call and function call for a given object.

Here is short description how this feature would look like

https://isocpp.org/blog/2016/02/a-bit-of-background-for-the-unified-call-proposal

As far as I know, it didn't make it into C++17 (too late?), awaiting for c++2x

What do you mean by extension methods in C#?

Extension Methods are just static methods in static classes that behaves like they were defined in other class.

In the first parameter before the type goes the keyword this wich indicates that is an extension method.

Example:

public static class Extensions
{
public static object ExtensionMethodForStrings( this string s, object otherParameter)
{
//....
return //whatever you want to return or not
}
}

This is an extension method on System.String that takes two parameters:
- string s : This is the instance variable
- object otherParameter: You can have as many as you want including none

You can call this method in two ways:

Static way:

string s = "Your string";
object o = new object(); // or whatever you want
object result = Extensions.ExtensionMethodForStrings(s,o);

Extension Method way

string s = "Your string";
object o = new object(); // or whatever you want
object result = s.ExtensionMethodForStrings(o);

In the second case it works as if the type string has an instance method called ExtensionMethodForStrings. Actually for the compiler the are equivalent.

Are extension methods an object-oriented feature of C#?

Extension methods are not an object oriented language feature. (compared to: classes, inheritance, polymorphism etc).

Like every language feature, it should be used where it is appropriate and for what it is designed for. There are already dozens of questions about when and how to use Extension methods.

  • What are the best practices for using Extension Methods in .Net?
  • Possible overuses of Extension Methods
  • Do Extension Methods Hide Dependencies?

Extension methods in c++

Different languages approach development in different ways. In particular C# and Java have a strong point of view with respect to OO that leads to everything is an object mindset (C# is a little more lax here). In that approach, extension methods provide a simple way of extending an existing object or interface to add new features.

There are no extension methods in C++, nor are they needed. When developing C++, forget the everything is an object paradigm --which, by the way, is false even in Java/C# [*]. A different mindset is taken in C++, there are objects, and the objects have operations that are inherently part of the object, but there are also other operations that form part of the interface and need not be part of the class. A must read by Herb Sutter is What's In a Class?, where the author defends (and I agree) that you can easily extend any given class with simple free functions.

As a particular simple example, the standard templated class basic_ostream has a few member methods to dump the contents of some primitive types, and then it is enhanced with (also templated) free functions that extend that functionality to other types by using the existing public interface. For example, std::cout << 1; is implemented as a member function, while std::cout << "Hi"; is a free function implemented in terms of other more basic members.

Extensibility in C++ is achieved by means of free functions, not by ways of adding new methods to existing objects.

[*] Everything is not an object.

In a given domain will contain a set of actual objects that can be modeled and operations that can be applied to them, in some cases those operations will be part of the object, but in some other cases they will not. In particular you will find utility classes in the languages that claim that everything is an object and those utility classes are nothing but a layer trying to hide the fact that those methods don't belong to any particular object.

Even some operations that are implemented as member functions are not really operations on the object. Consider addition for a Complex number class, how is sum (or +) more of an operation on the first argument than the second? Why a.sum(b); or b.sum(a), should it not be sum( a, b )?

Forcing the operations to be member methods actually produces weird effects --but we are just used to them: a.equals(b); and b.equals(a); might have completely different results even if the implementation of equals is fully symmetric. (Consider what happens when either a or b is a null pointer)

Extension methods not working for int?

Adding a public access specifier to the extension method should fix the issue.

public static class NumberExtentions
{
public static string Format(this int integer)
{
return string.Format("{0:n0}", integer);
}
}

See Dot Net Fiddle

How can I create .Net extension methods by C++/CLI?

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) {
...
}
};

How do extension methods work under-the-hood?

How do extension methods work under-the-hood?

They're just static methods; the compiler rewrites calls like myObject.MyExtensionMethod() to MyExtensionClass.MyExtensionMethod(myObject).

Is it better to use inheretance or extension methods on WELL-KNOWN classes that you OWN?

There's not single answer to this question, it all depends on the context. But usually extension methods are most useful in those cases:

  • you don't own the code for the extended type
  • the method targets an interface and will be the same for all implementations of this interface (e.g. IEnumerable<T> and Linq extension methods)


Related Topics



Leave a reply



Submit