In Visual Objects, you could define methods to classes where you had no sources and that are defined in other libraries.
In the .NET Framework this is not possible, but since this is a very powerful language feature, you can use the
Extension methods to attach methods to another class where you have no sources. This works even with system classes and base datatypes (Everything is an object).
Please look at this code:
local cString as string local cResult as string cString := "Hello world!" cResult := cString:Left( 5 )
System.String class has no
The solution is this one:
static class StringExtensions static method Left( self cString as string, nLen as int ) as string local cReturn as string if nLen >= cString:Length cReturn := cString else cReturn := cString:Substring( 0, nLen ) endif return cReturn
The secret stays in the first parameter:
self cString as string
If you have defined this extension method in an assembly with a different namespace, this namespace of course must be included by a
And if you look at the sample code, you will see that the length of the string is checked before the
SubString() method is called to be sure no exception is created if the string is shorter than indicated in the parameter. For more details see the Exceptions topic.