Beauty of dynamics

I’ve never liked the out keyword. I know, it’s personal, and you are welcome to disagree with me.

The TryParse pattern happens quite often. My preferred approach is wrapping both return values into an object. Or use KeyValuePair. But it’s not an elegant solution for my taste.

That is one of the reasons I liked seeing Tuples in C# 4.0. But still … not elegant enough. Here comes dynamic. I worked with dynamic languages since … well, long enough. But it didn’t “click” with C#. But today, I was doing some code where I wanted to return an instance of the anonymous class. Something similar to this:

 return customerList.Select(c => new {Id = c.Id, Name = c.Name}); 

And I’ve realized that there is a nice way of handling this situation (as well as TryParse pattern) the following way:

 private object GetNew() { return new { Id = 5, Name = "Joe Doe"; }; }</span></p>
<p><span style="font-size: 16px;">[TestMethod] public void Get_anonymous_object_with_dynamic() { dynamic newObj = GetNew();</span></p>
<p><span style="font-size: 16px;">Assert.AreEqual(5, newObj.Id); Assert.AreEqual("Joe Doe", newObj.Name); } 

So, I’m quite happy with this solution … for now.


Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s