Dynamic Is More Than a Keyword

by Doug Finke on August 18, 2010

in .NET 4.0,C# 4.0,Dynamic Keyword,PowerShell,Ruby

Rob Conery’s post Redlining C#’s Dynamic Features shows Ruby source and then explores the C# 4.0 dynamic keyword feature to achieve the same results.

So to get my head around the Ruby example, I worked up one way to do it in PowerShell using the New-Module cmdlet, wrapped it in a function and you can see the code below.

Like Ruby, PowerShell lets us assign a string to Address in the first example ($p1) and then in the second example ($p2) to a more complex object without breaking the Person implementation.

Rob Conery’s post goes on to show that C# 4.0 can do the same thing. The dynamic dial is being turned up for this static language.

Rob suggests:

C# is going more and more dynamic – time and feature set have proven that. Maybe it’s time to bend your thinking? Or maybe it’s not…

In either case it is possible to do and should make for interesting discussions.

Function New-Address {            
    New-Module -AsCustomObject -Name Address {            
        $Number  = $null            
        $Street  = $null            
        $City    = $null            
        $State   = $null            
        $Country = $null            
        Export-ModuleMember -Variable *            
Function New-Person {            
    New-Module -AsCustomObject -Name Person {            
        $Name    = $null            
        $Address = $null                    
        Export-ModuleMember -Variable *            
$p1 = New-Person            
$p1.Name = "Mary"            
$p1.Address = "Number 17, Cherry Tree Lane"            
$p2 = New-Person            
$p2.Name = "Burt"            
$p2.Address = New-Address            
$p2.Address.Number = 17            
$p2.Address.Street = "Cherry Tree Lane"            
$p2.Address.City = "London"            
# Result            
Address                                                              Name
-------                                                              ----
Number 17, Cherry Tree Lane                                          Mary
@{City=London; Country=; Number=17; State=; Street=Cherry Tree Lane} Burt

{ 1 comment… read it below or add one }

JESSE DZIEDZIC 10.20.11 at 2:04 am

Youre indeed right on this writing!

Leave a Comment

You can use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>

Previous post:

Next post:

You are forbidden!