Use Dynamic to Ditch the Boring Code

Chris Missal

Use Dynamic to Ditch the Boring Code

A.K.A.

Agenda

  1. Wait?! Dynamic in .Net?
  2. How does it work?
  3. When to use it
  4. When to avoid it
  5. Examples and samples

Dynamic in .NET

The concept of dynamic in .NET (DLR) has been around since Nov/Dec 2008.

Agenda

  1. Wait?! Dynamic in .Net?
  2. How does it work?
  3. When to use it
  4. When to avoid it
  5. Examples and samples

ExpandoObject Example

			dynamic student = new ExpandoObject();
student.FirstName = "Jeff";
student.LastName = "Lebowski";
		

DynamicObject Example

			public class SampleDynamicObject : DynamicObject { }
// ...
dynamic sampleObject = new SampleDynamicObject ();
// ...
public override bool TryGetMember(
    GetMemberBinder binder, out object result)
public override bool TrySetMember(
    SetMemberBinder binder, object value)
		

DynamicObject (continued)

			public override object TryInvokeMember(
	InvokeMemberBinder binder, object[] args,
	out object result)
		

Agenda

  1. Wait?! Dynamic in .Net?
  2. How does it work?
  3. When to use it
  4. When to avoid it
  5. Examples and samples

When to use it

A bit more on Views

Think outside the box

Agenda

  1. Wait?! Dynamic in .Net?
  2. How does it work?
  3. When to use it
  4. When to avoid it
  5. Examples and samples

When to avoid it

Agenda

  1. Wait?! Dynamic in .Net?
  2. How does it work?
  3. When to use it
  4. When to avoid it
  5. Examples and samples

Dynamic Configuration

Flexible Code + Configuration

Configuration in .Net applications can contain several lines in a file that reference <add key="name" value="stuff"/>. Developers can put all kinds of data in these and getting them out is annoying.

Here's how it works:

Sample app.config
			<add key="Retries" value="5"/>
			<add key="BuildDate" value="2012-02-13/>
		
Usage with Formo
			var retries = config.Retries; // or config.Retries(10);
			DateTime dt = config.BuildDate<DateTime>();
		

Time for
real code!

Pros - Formo benefits from dynamic by:

  1. Not relying on "magic strings"

Cons - Formo is terrible because:

  1. Dynamic code can be slow

More on this in a moment...


Performance

Performance

Another Project, Freddie

I'd like to talk to an API that lets me send work with an email service provider.

All the implementations I can find want me to use a crazy amount of static types.

Dynamic!

Why Use Dynamic?

Let's recap:

  • It crosses a process boundary
  • HTTP is already dynamic, keep it that way
  • Freddie's should let clients talk to MailChimp and not get in the way
  • Keeps Freddie "ignorant" of the API

Your (optional) homework

  PM> Install-Package Formo

Thanks! Questions?

Chris Missal, Headspring