Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How is the upcoming 'dynamic' keyword in .net 4.0 going to make my life better?

Tags:

.net

c#-4.0

I don't quite get what it's going to let me do (or get away with :)

like image 313
PaulB Avatar asked Mar 27 '09 10:03

PaulB


People also ask

Why do we need dynamic in C#?

It is used to avoid the compile-time type checking. The compiler does not check the type of the dynamic type variable at compile time, instead of this, the compiler gets the type at the run time. The dynamic type variable is created using dynamic keyword.

Is C# dynamically typed?

Programming languages are sometimes divided into statically typed and dynamically typed languages. C# and Java are often considered examples of statically typed languages, while Python, Ruby and JavaScript are examples of dynamically typed languages.


2 Answers

The two big areas are:

  • working with COM assemblies where methods return vague types - so you can essentially use late binding
  • working with DLR types

Other uses include things like:

  • duck-typing where there is no interface
  • Silverlight talking to the host page's DOM
  • talking to an xml file.

In C# itself, this allows a few things, such as a basic approach to generic operators:

static T Add<T>(T arg1, T arg2) { // doesn't work in CTP
     return ((dynamic)arg1) + ((dynamic)arg2);
}

(of course, I'd argue that this is a better (more efficient) answer to this)

like image 180
Marc Gravell Avatar answered Nov 04 '22 17:11

Marc Gravell


From Charlie Calvert's blog:

Useful Scenarios

There are three primary scenarios that will be enabled by the new support for dynamic lookup:

  1. Office automation and other COM Interop scenarios
  2. Consuming types written in dynamic languages
  3. Enhanced support for reflection

Read more here: http://blogs.msdn.com/charlie/archive/2008/01/25/future-focus.aspx

like image 25
CraigTP Avatar answered Nov 04 '22 16:11

CraigTP