Dan Holmes <da*******@bigfoot.com> wrote:
Isn't CreateInstance(typeof(int)) the same as CreateInstance<int>()?
i don't understand how this method helps anything.
It's the implementation of ": new()" and "new T()". It also leaves an
avenue to the CLR folks to dynamically bind to the corresponding
constructor so that reflection doesn't have to be used.
It isn't currently optimized (check it out with SOS and !u) - but that
path is available to future runtimes.
Test program:
---8<---
using System;
class App
{
class A {}
class B : A {}
static void Main()
{
A a = Activator.CreateInstance<A>();
B b = Activator.CreateInstance<B>();
}
}
--->8---
The contents of App.Main, unassembled with WinDbg, SOS, !u:
---8<---
mov ecx,0x9230f8
(MD: System.Activator.CreateInstance[[App+A, Test]]())
call mscorlib_ni+0x2edd58 (793add58)
(System.Activator.CreateInstance[[System.__Canon, mscorlib]](),
mdToken: 06000399)
mov ecx,0x9231b0
(MD: System.Activator.CreateInstance[[App+B, Test]]())
call mscorlib_ni+0x2edd58 (793add58)
(System.Activator.CreateInstance[[System.__Canon, mscorlib]](),
mdToken: 06000399)
ret
--->8---
You can see there that the actual method called for both invocations of
CreateInstance is the preJITted one at 793add58, so it must be using
reflection in order to get the job done.
-- Barry
--
http://barrkel.blogspot.com/