Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why use dynamic typing in c#?

At first I thought something like:

var aName=getAllSomethings();

Is very unreadable, and so I'll use dynamic typing just when there's no room for confusion such as:

AClassName aName = new AClassName();

Here,

var aName=new AClassName();

seems readable. But than I read (here) that dynamic typing also comes with a price in performance.
I tried reading all the other posts in that link to understand where I should use dynamic typing, but couldn't come up with even one good reason. Should I just wait for when I'll tell myself - "This can only be solved with dynamic typing" ? Or are there better (practical) reasons for using it?

Thanks.

Edit: My mistake (-: will close this question ASAP.

like image 779
Oren A Avatar asked Sep 05 '10 21:09

Oren A


People also ask

What is the point of dynamic typing?

Advantages of dynamically-typed languages:The absence of a separate compilation step (which is much more common) means that you don't have to wait for the compiler to finish before you can test changes that you've made to your code. This makes the debug cycle much shorter and less cumbersome.

What are the advantages of dynamic type checking?

Advantage of Dynamic Type Checking Dynamic type checking can find many errors that cannot be identified by static type checking. In most languages, static type checking is not possible for some language constructs in certain cases but the same purpose can be achieved by dynamic type checking.

What is the use of dynamic typing give an example?

In Dynamic Typing, type checking is performed at runtime. For example, Python is a dynamically typed language. It means that the type of a variable is allowed to change over its lifetime. Other dynamically typed languages are -Perl, Ruby, PHP, Javascript etc.

What is dynamic typing in C?

A variable is dynamically typed when the type of the object it points to is not checked at compile time. Objective-C uses the id data type to represent a variable that is an object without specifying what sort of object it is. This is referred to as dynamic typing.


1 Answers

var isn't dynamic typing. It's just that the type of aName is inferred by the compiler.

Your example is still entirely statically typed, and has no performance penalty. Your code is compiled into exactly the same IL as it would be with an explicit type name.

Now in C# 4, dynamic typing does exist, but it would be written as:

dynamic aName = new AClassName();

My personal belief is that dynamic typing will be relatively rarely useful in C# 4 - basically when you're dealing with data which is already only known dynamically, e.g. reflection, or navigating XML.

like image 145
Jon Skeet Avatar answered Sep 28 '22 22:09

Jon Skeet