Extension methods: Adding methods to classes without deriving (with a simple StringTheory example)

While coding a recent project I wrote something like this to call StringTheory to Append a Value with a ' ' Space Separator before the Value:

st.Append(ValueOne,st:clip,' ')
st.Append(ValueTwo,st:clip,' ')
st.Append(ValueThree,st:clip,' ')

It works perfectly fine, but it adds some repetitive code that hurts a little the code readability.

Trying to simplify this, I wrote some tests, and after getting a compiler error I recalled that for the compiler it’s the same to call SomeProc(object) or object.SomeProc().

This means we can declare global procedures that can add methods to classes without creating a derived class, like C# extension methods.

For example, the above code can be written as:

st.AppSp(ValueOne) !Append with clip and space separator before
st.AppSp(ValueTwo)
st.AppSp(ValueThree)

by globally declaring something like:

  MAP
AppSp   PROCEDURE(StringTheory pSt,STRING pText) !Append with clip and space separator before
  .

AppSp   PROCEDURE(StringTheory pSt,STRING pText)
  CODE 
  pSt.Append(pText,st:clip,' ')

and the new method will be available for all instances of StringTheory. Here’s a test project on github.

Of course, this is only trivial syntactic sugar, but it may be used as a simple way to add custom functionality to third party or ABC classes.

Hope you find it interesting.

Carlos

3 Likes

You can also use this to create private methods that don’t get published in the inc file.

1 Like