Safari Books Online is a digital library providing on-demand subscription access to thousands of learning resources.
382 C HAPTER 14 Extending IronPython with C#/VB.NET must have a different type signature. Unfortunately, this makes having several optional arguments of the same type impossible just through overloads. Listing 14.13 shows what we can do with VB . NET . The Example class here has Default- Values and MultipleArguments methods that do the same as their C# equivalents. Listing 14.13 Optional and multiple arguments from VB.NET Public Class Example Public Shared Sub DefaultValues(ByVal string1 As String, _ Optional ByVal string2 As String = "default", _ Optional ByVal string3 As String = "another") Console.WriteLine("First argument = " + string1) Console.WriteLine("Second argument = " + string2) Console.WriteLine("Third argument = " + string3) End Sub Arguments declared as optional Public Shared Sub MultipleArguments( _ ByVal ParamArray args() As Object) Taking multiple arguments Dim len As Integer = args.Count with ParamArray Console.WriteLine("You passed in {0} arg", len) For i As Integer = 0 To UBound(args, 1) Print all the Dim arg As Object = args(i) arguments Console.WriteLine("Argument {0} is {1}", i, arg) Next End Sub End Class Designing an API is one of the most important tasks in programming. It influences the structure and usability of your application or libraries. This is why I am a fan of test- driven development; it makes you think about the usability of your API before you think about the implementation. We've been looking at ways to give an API written in C# or VB . NET that elusive Pythonic quality when used from IronPython. Of course, the easiest way to achieve this is to write your code in Python in the first place, but it may not always be possible. We have already shown how using attributes from IronPython requires the writing of at least some code in a more traditional . NET language, whether it be a stub class or a thin wrapper around native functions. In particular, writing stub classes can feel like mechanical work, ripe for automation. In fact, we can automate the compiling of these classes from text (which, after all, is what the compiler does), which means we could automate the generation of the stubs at runtime! In the next section we use some of the API s available in . NET that allow us to dynamically compile (and then use) code at runtime. 14.3 Compiling and using assemblies at runtime The code we wrote earlier to wrap native functions for WindowUtils was brief, but having to maintain a separate Visual Studio project and recompile and then copy assemblies across every time we changed the code could be annoying. We can avoid this, and actu- ally eliminate the need to even save binary assemblies at all, by compiling straight from source code into memory!