Dynamic Typing

In my last post, I talked about Duck Typing and I said it is one of the principle of Dynamic Typing, but don’t have to be in a dynamically typed language.

In order to discuss Dynamic Typing, we need to go thorough other typing systems and know the differences between them

Implicit Typing (or Type Inference) [C# 3.0 and later]:

It is one of the forms of Latent Typing as well as Duck Typing and Dynamic Typing. Let’s see this example

var test = 5; // test is an integer

Here, you don’t have to specify the type as the Compiler can infer from the statement that the variable will hold an integer. That’s why it cannot be used if declaration and assignment are not on the same statement…

var test; // Compilation error
test = 5;

Implicit typing is used mainly when the developer wants to use the result of a function, or an expression (as in LINQ) without the need to specify its type, as the compiler already knows the type. Also, if Explicit casting is used, there is no need for explicit typing…

var test = (int) cmd.ExecuteScalar();

Dynamic Typing [Ruby, Python, and C# 4.0]

It is another form of Latent Typing, but unlike Implicit typing, type is deduced at runtime, so, there is no type checking at compile time. The support for dynamic typing is introduced in C# 4.0 to support API calls into dynamic type languages, or the use of other non-typed data, like XML.

XElement element = XElement.Parse(@"
    <FirstName>John</FirstName>
    <LastName>Smith</LastName>
    </Person>");
dynamic personXml = new DynamicXml(element);
personXml.FirstName = "Bob";

It is important to know that once a variable type is defined at runtime, it cannot be redefined later as another type. i.e. Dynamic Typing is not Weak Typing

Weak Typing (or Loose Typing) [Javascript, VB 6.0]

In javascript, this code is valid

var x = new Array(); // Any array
x[0] = "One"; // First element is a string, other elements can be any type
x[1] = "two";
x[2] = "three";
alert(x.length); // return 3
x = x.join(""); // Now x is a string not an Array
alert(x.length); // now return 11 (string length)

Weak typing is antonym to Strong Typing, while Dynamic Typing is antonym to Static Typing.

Here are some good related articles about typing systems by Bruce Eckel (author of Thinking in C++ and Thinking in Java):

Strong Typing vs. Strong Testing
About Latent Typing
How to Argue about Typing
I’m Over It

Advertisements

2 thoughts on “Dynamic Typing

Leave a Reply

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

WordPress.com Logo

You are commenting using your WordPress.com 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