Talking about performance, what is better in C#? Use Dynamic types or Typecast?
Like this (just an example, not the real implementation):
var list = new List<object>();
list.Add(new Woman());
list.Add(new Men());
list.Add(new Car());
....... in another code ....
var men = (Men)list[1];
men.SomeMenMethod();
Or this
var list = new List<dynamic>();
list.Add(new Woman());
list.Add(new Men());
list.Add(new Car());
....... in another code ....
var men = list[1];
men.SomeMenMethod();
If possible, don’t use either. Try to use type-safe solution that doesn’t involve casting or
dynamic.If that’s not possible, casting is better, because it’s more clear, more type-safe (compiler can check that
Menactually does haveSomeMenMethod), the exception in case of an error is clearer and it won’t work by accident (if you think you haveMen, but you actually haveWoman, which implements the same method, it works, but it’s probably a bug).You asked about performance. Nobody other than you can really know the performance of your specific case. If you really care about performance, always measure both ways.
But my expectation is that
dynamicis going to be much slower, because it has to use something like a mini-compiler at runtime. It tries to cache the results after first run, but it still most likely won’t be faster than a cast.