Dynamic Programming in C# 4.0 – An Overview

One of the most interesting additions to C# 4.0, I think, is the dynamic addition. Just thinking about this makes me excited. I will jump right into a little theory then some code.

The Theory of Dynamic

So what is this here dynamic thingy? dynamic in C# 4.0 refers to dynamic binding and dynamic binding is what happens at runtime and not at compile time. This involves binding a method, property, operator, member etc of an object at runtime. Yes I know this sounds like polymorphism or like the var keyword or even like using the ultimate base class in C# – object. First and foremost you have to let go or what you know and remember this important fact.

dynamic != var && dynamic != object

The keyword dynamic, casually speaking, tells the compiler that “Even though it cannot resolve the member statically, it should trust the programmer and don’t worry because it will/may be resolved at runtime.”


Here is a sample on how you use the dynamic keyword:

dynamic dyn = “My first time”;

Now let’s look at some similarities and differences of var, object, and dynamic for a sec.

var v = 1; // here the compiler will figure out (at compile time) the type for v which will be int.
//v.Compute(); // causes a compiler error
object o = 1; // this is boxed from value type to an object with type being int32
//o.Compute(); //also gives a compiler error
dynamic d = 1; //type here is int32
d.Compute(); // does not give compile time error but will throw a runtime RuntimeBinderException

Continue reading


Simple Tips To Help You Write Friendlier Code

Clean Code.

To paraphrase BJarne Stroustrop, Clean Code is elegant, simple and efficient and does one thing well. I particularly love this statement because it has always been a strong belief of mine. I will now attempt to go through a few simple every day checklist that can improve code readability and ultimately, maintainability.  

Tip #1: Identifiers

Identifiers, functions, classes/interface, should have names that are clear and concise. Most developers, including myself, love to write code late at night. This is when we can crank out our latest and greatest. But if you are like me, when you look at that same piece of art you cranked out a few weeks ago (or even the night before), you can hardly recognize what the variable call killSwitchForCat means. 

Below is a table of good and bad identifiers just to give an idea.

Bad Good
int w = dayOfMonth/7; // what is ‘w’ in the equation int week = dayOfMonth/7;  //Write what was intended
int l; // don’t know if this is 1 or lowercase L int length; // This is more easily identified and is even more searchable in Visual Studio

  Continue reading