User Tools

Site Tools


attached_methods

Differences

This shows you the differences between two versions of the page.

Link to this comparison view

Next revisionBoth sides next revision
attached_methods [2018/01/28 17:24] – created wolfgangriedmannattached_methods [2018/01/28 17:35] wolfgangriedmann
Line 1: Line 1:
 ====== Attached methods ====== ====== Attached methods ======
 +
 +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 ''Attached methods'' to attach methods to another class where you have no sources. This works even with system classes and base datatypes ([[everything_object|Everything is an object]]).
 +
 +Please look at this code:
 +<code>local cString as string
 +local cResult as string
 +
 +cString := "Hello world!"
 +cResult := cString:Left( 5 )</code>
 +
 +But the ''System.String'' class has no ''Left()'' method!
 +
 +The solution is this one:
 +<code>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</code>
 +The secret lies in the first parameter: 'self cString as string''
 +
 +If you have defined this attached method in an assembly with a different namespace, this namespace of course must be included by a ''using'' statement
 +
 +
  
attached_methods.txt · Last modified: 2018/01/28 17:41 by wolfgangriedmann