Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When should one use dynamic keyword in c# 4.0?

When should one use dynamic keyword in c# 4.0?.......Any good example with dynamic keyword in c# 4.0 that explains its usage....

like image 477
ACP Avatar asked Apr 20 '10 12:04

ACP


People also ask

What is the dynamic keyword used for?

The dynamic keyword is used to declare dynamic types. The dynamic types tell the compiler that the object is defined as dynamic and skip type-checking at compiler time; delay type-checking until runtime. All syntaxes are checked and errors are thrown at runtime.

When should you use dynamic in C#?

In C# 4.0, a new type is introduced that is known as a dynamic type. 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.

What is use of dynamic keyword in C#?

The dynamic keyword is new to C# 4.0, and is used to tell the compiler that a variable's type can change or that it is not known until runtime. Think of it as being able to interact with an Object without having to cast it.


2 Answers

Dynamic should be used only when not using it is painful. Like in MS Office libraries. In all other cases it should be avoided as compile type checking is beneficial. Following are the good situation of using dynamic.

  1. Calling javascript method from Silverlight.
  2. COM interop.
  3. Maybe reading Xml, Json without creating custom classes.
like image 58
Amitabh Avatar answered Oct 23 '22 13:10

Amitabh


How about this? Something I've been looking for and was wondering why it was so hard to do without 'dynamic'.

interface ISomeData {} class SomeActualData : ISomeData {} class SomeOtherData : ISomeData {}  interface ISomeInterface {     void DoSomething(ISomeData data); }  class SomeImplementation : ISomeInterface {     public void DoSomething(ISomeData data)     {         dynamic specificData = data;         HandleThis( specificData );     }     private void HandleThis(SomeActualData data)     { /* ... */ }     private void HandleThis(SomeOtherData data)     { /* ... */ }  } 

You just have to maybe catch for the Runtime exception and handle how you want if you do not have an overloaded method that takes the concrete type.

Equivalent of not using dynamic will be:

    public void DoSomething(ISomeData data)     {         if(data is SomeActualData)           HandleThis( (SomeActualData) data);         else if(data is SomeOtherData)           HandleThis( (SomeOtherData) data);         ...         else          throw new SomeRuntimeException();     } 
like image 25
user2415376 Avatar answered Oct 23 '22 12:10

user2415376