I have started using C# 4.0 and loving the dynamic keyword. However, I am not sure what I am doing can be considered as good practice. Please see the code below:
static void Main()
{
NoobSauceObject noob = new NoobsauceObject();
dynamic theReturnType = noob.do(param);
if (theReturnType.GetType().ToString().Contains("TypeOne"))
theReturnType.ExecuteMethodOfTypeOne();
else if (theReturnType.GetType().ToString().Contains("TypeTwo"))
theReturnType.ExecuteMethodOfTypeTwo();
else
throw new ArgumentException("");
}
Is there a better way of doing this? I found the above method quite easy and have been using it but not sure if it is something I should stick with in the long run.
EDIT: If I were to do the same using .NET 3.5 or lower, or without the dynamic keyword, what would be a good implementation?
Thanks in advance!! 🙂
It looks to me like you’re just doing a type-test between two unrelated types. If possible, I’d look at polymorphism here, or at least: implementing a common interface. However, the following would be fine too:
However, my preferred option is:
where
TypeOneandTypeTwomight use explicit interface implementation to expose the method on their API:(and likewise
TypeTwo)I can see no real use for
dynamichere; For the return type ofnoob.do(param),objectwould be fine in the first example – orISomeInterfacewould be even better.