Skip to content

Extension Methods: What can I extend?

In Xojo, extension methods are methods that, while not part of the original definition of a type, are treated as though they are part of that data type.

The Xojo documentation says:

The Extends keyword allows you to call a user-defined method as if it were part of a class. You use the Extends keyword only for the first parameter in the method declaration. Extends indicates that this parameter is to be used on the left side of the dot operator. The remaining parameters in the declaration, if any, are used normally.”

What this means is that for something like a string you can use an extension method to add your own methods to that type. So if you want to have a concise means of telling if one string contains another without having to remember the instr syntax, you can add a method, as follows, to a module (perhaps named StringExtensions):

Function Contains(Extends Container as String, Contained as String) as Boolean
  Return Container.InStr(Contained) > 0
End Function

Now you can use it in any of your own code, like the following, as if strings had always had a “contains” method:

   if thisString.Contains(thatString) then
    // do something special
   end if

Now you can add your own method after the fact.

Note that the compiler allows you to extend any data type so you can extend classes, the intrinsic types, and even class interfaces! I have to admit that I’d never thought of extending an interface until I read a bug report from a long-time Xojo user about how autocomplete didn’t work where they extended an interface.

You can read more about Extends in the Xojo Documentation and check our this post about Using Extension Methods.