#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

About Sean
Software developer in the Twin Cities area, passionate about .NET technologies. Equally passionate about my own personal projects related to family history and preservation of family stories and photos.

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 )

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

Follow

Get every new post delivered to your Inbox.

Join 43 other followers