What is the difference between Assembly.GetExecutingAssembly()
and typeof(program).Assembly
?
In C#, GetExecutingAssembly() method is the method of Assembly class. This method returns the assembly that contains the code that is currently executing. To use this method we have to use System. Reflection in our program.
The recommended way to retrieve an Assembly object that represents the current assembly is to use the Type. Assembly property of a type found in the assembly, as the following example illustrates. To get the assembly that contains the method that called the currently executing code, use GetCallingAssembly.
System. Reflection. Assembly. It defines an assembly, which is a reusable, versionable and self describing building block of a Common Language Runtime.
Assuming program
is in the executing assembly, they should both return the same value. However, typeof(program).Assembly
should have better performance, since Assembly.GetExecutingAssembly()
does a stack walk. In a micro benchmark on my machine, the former took about 20ns, while the latter was 30x slower at about 600ns.
If you control all the code I think you should always use typeof(program).Assembly
. If you provided source code that other people could build into their assemblies, you would need to use Assembly.GetExecutingAssembly()
.
Calling Assembly.GetExecutingAssembly()
will return the assembly containing the method that is calling Assembly.GetExecutingAssembly()
.
Calling for example typeof(string).Assembly
will return mscorlib.dll because it contains the type String
. On the other hand if you have a project called MyProject and somewhere in this project you call Assembly.GetExecutingAssembly()
it will return the Assembly instance representing MyProject.dll
Hope this clarifies.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With