Under which application development scenarios C# dynamics and ExpandoObject can be used or when to consider using c# dynamics and ExpandoObject
0
One scenario where I’ve seen dynamic used effectively was in the implementation of feature toggles.
We had a globally accessible FeatureToggles
class which was a dynamic object, therefore in our code we could make certain features of the code dependent on the toggle being enabled eg:
public void DoSomething()
{
if (FeatureToggles.SomeFeatureEnabled)
{
DoSomeFeature();
}
}
The feature toggles were configured in the application configuration file, and the dynamic FeatureToggles
object read the app config at startup. If a feature toggle was enabled in the config, the FeatureToggles
class would return true; if a feature toggles was not enabled, or was not yet in the configuration file, the FeatureToggles
class would return false. Crucially, this enabled us to start using feature toggles before they had even been configured*, in which case they defaulted to off.
* naturally there was logging output in this case.
One edge case where dynamic
is not necessary, but can make your code more DRY and not actually less type-safe is when implementing the visitor pattern.
The classical way to implement this is to have an Accept(Visitor visitor)
method on each derived type and you have to implement it with the same visitor.Visit(this)
boilerplate.
And this assumes the types in question support the visitor. If not, you need one big if (obj is DerivedType1) … else if (obj is DerivedType2) … else if …
and modify it each time new type is added (along with adding the overload of Visit()
for the new type).
With dynamic
, it’s a matter of single line to cast your type to dynamic
, which means the correct overload will be chosen:
public void Visit(BaseType obj)
{
VisitInternal((dynamic)obj);
}
protected virtual void VisitInternal(DerivedType1 obj)
{
}
protected virtual void VisitInternal(DerivedType2 obj)
{
}
// etc.
This might be my personal opinion but : Never
You are using C#. Static typed language. And probably one of the reasons why are you using it is because you like the safety of static typing for various reasons. If you wanted to sacrifice it, you would be using real dynamic language like Python or Ruby.
3