In C# dynamic key word performance?

If use dynamic Key Word & we assign some Type on it, is Compiler perform boxing/un-boxing Operation? For Example;

dynamic myInstance=null;
object key="BankProject.Payment";
Type myType=ServiceCashe.GetType(key);//get desire type from cache...
myInstance=Activator.CreateInstance(myType); //instanciate myType
Jon Skeet
people
quotationmark

Unless it's a value type, there'll be no boxing going on - but in the code sample you've used, there's no real use of dynamic typing anyway. Your code thus far is equivalent to:

object key = "BankProject.Payment";
Type myType = ServiceCashe.GetType(key);
object myInstance = Activator.CreateInstance(myType);

It's only when you perform dynamic member access - e.g. myInstance.SomeMethod() that dynamic typing would actually come into effect. Usually the way to avoid that is to make all the types that you're fetching dynamically implement some interface:

object key = "BankProject.Payment";
Type myType = ServiceCashe.GetType(key);
IPayment myInstance = (IPayment) Activator.CreateInstance(myType);
myInstance.SomeMethodInInterface();

Then the only "dynamic" parts are creating the instance, and then the execution-time check in the cast.

As always, if you have performance concerns you should measure them in realistic situations against well-defined goals. Even if this did perform boxing and unboxing, we would have no idea whether or not that was a significant cost in your context. (As it happens, boxing and unboxing are way cheaper in my experience than Activator.CreateInstance...)

people

See more on this question at Stackoverflow