Send() and IVarPut()/IVarGet() in X#

This forum is meant for examples of X# code.

Post Reply
User avatar
wriedmann
Posts: 3765
Joined: Mon Nov 02, 2015 5:07 pm
Location: Italy

Send() and IVarPut()/IVarGet() in X#

Post by wriedmann »

Sometimes, you could need a functionality like the Send(), IVarPut() and IVarGet() functions from Clipper also in X#
Fortunately, thanks to Reflection, this is possible, and thanks to the possibility to use extension methods, also easier to use.

A sample use could be:

Code: Select all

oObject:Send( cMethodName, oParameter ) 
oObject:PropertyPut( cPropertyName, oValue )
oValue := oObject:PropertyGet( cPropertyName )
This is the extension class that gives this functionality:

Code: Select all

using System                        
using System.Text
using System.Runtime.InteropServices
using System.Reflection 
using System.Diagnostics

static class ObjectExtensions

static method Send( self oObject as object, cMethod as string, aParameters as object[] ) as object 
local oType as System.Type
local oReturn as object
local oInfo as MethodInfo
	
oType := oObject:GetType()
oReturn := null_object
oInfo := oType:GetMethod( cMethod )
if oInfo != null_object
    oReturn := oInfo:Invoke( oObject, aParameters )
endif
	
return oReturn              

static method PropertyGet( self oObject as object, cPropertyName as string ) as object
local oReturn as object	
local oInfo as System.Reflection.PropertyInfo
	
oInfo := oObject:GetType():GetProperty( cPropertyName ) 
if oInfo != null_object                                  
    oReturn := oInfo:GetValue( oObject, null_object ) 
else
    oReturn			:= null_object
endif
	
return oReturn

static method PropertyPut( self oObject as object, cPropertyName as string, oValue as object ) as void
local oInfo as System.Reflection.PropertyInfo
	
oInfo := oObject:GetType():GetProperty( cPropertyName )
if oInfo != null_object
    oInfo:SetValue( oObject, oValue, null_object )                        
endif
	
return

end class
Wolfgang Riedmann
Meran, South Tyrol, Italy
wolfgang@riedmann.it
https://www.riedmann.it - https://docs.xsharp.it
User avatar
robert
Posts: 4540
Joined: Fri Aug 21, 2015 10:57 am
Location: Netherlands

Send() and IVarPut()/IVarGet() in X#

Post by robert »

Wolfgang,

Nice how you have used the extension method to extend the OBJECT type and therefore make the methods available in every type.
This is in fact very similar to what happens in the Vulcan Runtime and what will happen in the new XSharp runtime for the Send() function and IVarGet() and IVarPut() functions.

The biggest difference for these functions is that they cache the MethodInfo and PropertyInfo and for properties that they also do a lookup for (public) fields, since the VO language allows late bound access to public fields as well.

Robert
XSharp Development Team
The Netherlands
robert@xsharp.eu
Post Reply