PowerShell and the dynamic keyword in C# 4.0

March 7th, 2009 / Development in a Blink

The dynamic keyword in C# 4.0 simplifies the interaction with PowerShell variables. C#’s var keyword casts the GetVariable as an object and needs additional code to cajole the object array into a shape that could be worked with.

The embedded PowerShell below creates 4 variables.

  • $a – An array of ints piped through a where and foreach
  • $b – A hash table
  • $c – A simple array
  • $d – A string

Printing the string variable results in printing each character.

Next up, using PowerShell’s Add-Member to add a NoteProperty, ScriptProperty and ScriptMethod to a PowerShell object and doing late-bound access in C#. I’ve experimented a bit but no success.

image

image

Results

image

Some References

Using the dynamic keyword is being experimented with other dynamic languages and other ways.

Comments are closed.