When should one use dynamic keyword in c# 4.0?.......Any good example with dynamic keyword in c# 4.0 that explains its usage....
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.
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.
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.
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.
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(); }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With