Dynamic Languages and The .Net Framework - Promo #2
This is the second promo post to my session at Developer Academy III. The rest of the series:
Now to the post...
The Task: Retrieve a value without the necessity to lose the type benefits.
Sometimes you want to a method to retrieve a value from somewhere. C# offers you a few solutions - you can return object, you can return a class (or struct) that has StringValue, IntValue, DateValue and so on properties (I've seen this solution too many times), you can create a generic return type that involves reflection (I've written a post about that on my old blog) or you can create several different methods.
All of the above solutions will work for sure, but what if you could write:
---- IronRuby code ----
def get_value(key)
case key
when :StringValue
return "Hello World"
when :IntValue
return 10
when :FloatValue
return 1.618
end
end
puts "StringValue: " + get_value(:StringValue)
puts "IntValue: " + (get_value(:IntValue) * 5).to_s
puts "FloatValue: " + (get_value(:FloatValue) - 1).to_s
---------------------------
The output you'll get is:
StringValue: Hello World
IntValue: 50
FloatValue: 0.618
It can be as simple and intuitive as that... and it's just at the tip of your finger!
The next post in the series will take this one step even further, stay tuned!
Haven't had enough? come to my session at Developer Academy III! :)
All the best,
Shay.