#182 – C# is (Mostly) Strongly Typed

Traditionally, C# has been considered as a strongly typed language.  But with the addition of the dynamic keyword in C# 4.0, you can choose to declare and use dynamically typed variables.  These variables are not type-checked at compile time, but only at run-time.

For example, the following code will not compile.  The String.Concat method is being used incorrectly.  (It’s a static method).

            string s = "Et tu";
            s = s.Concat(" Brutus");   // Compile-time error

In the following example, we declare the variable as dynamic, which means that the type of the variable is only determined at run-time.  No type-checking is done at compile-time.  This code will now compile fine.  The error will only be found at run-time, when an exception is thrown.

            dynamic s = "Et tu";
            s = s.Concat(" Brutus");   // This compiles
Advertisements

About Sean
Software developer in the Twin Cities area, passionate about software development and sailing.

One Response to #182 – C# is (Mostly) Strongly Typed

  1. Pingback: #183 – Use var to Tell the Compiler to Figure out the Type « 2,000 Things You Should Know About C#

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 )

Google+ photo

You are commenting using your Google+ 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 )

Connecting to %s

%d bloggers like this: