C Sharp implicit casting

DBJ dreaming in C# while lying on green grass
DBJ dreaming in C# while lying on the green grass

C Sharp implicit casting

February 13th, 2008

There might be something very interesting for you in FM#. Maybe a interesting example of the usage, of C# implicit casting operator? … Wait, what is FM#?

FM# is (my) C# library of Foundation Mechanisms (aka FM).

For a start, let me offer some magic. Lets look in the method cast() of the util class.  This method is used to get the value from the xml node, and cast it implicitly, to the C# variable of the same type. Reminder: value of the xml node is always an string.  Confusing. Let’s just use this then. Here is the method footprint:

 

Where “xmlnode” is the root node of the xml fragment to be used, “name” is the tag name of the required child node. “fallback” is optional argument used as a fallback value, optionally given if sub-node by given name is not found.

Return value is (of course)  interesting because it is an instance of the Implicitor class, also from the FM#  library.  This  method in effect “automagically” converts (xml) string values into the type of variable receiving the result of this method.  This is done through the magic of the Implicitor, which is the actual return type. Here is how.

In essence Implicitor is a class which transforms implicitly an object (given to its constructor) into the type of the variable on the left side of the assignment statement , aka “=”.

I am sure VB people will call this “VARIANT” type. Here we have the similar container of a single type less value, with implicit casting added. To make it useful. Here is the Implicitor use in its simplest form.

Above will work because “V” is of the correct type. An “int”. same as the type referenced inside the Implicitor, instance “i” above. This might seem as not a big deal … untill you see and understand its usage and potential, as in the util.cast() method, described first above.

DBJ