Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Difference between Assembly.GetExecutingAssembly() and typeof(program).Assembly

Tags:

c#

c#-4.0

What is the difference between Assembly.GetExecutingAssembly() and typeof(program).Assembly?

like image 393
Ravi Karthik Avatar asked Mar 14 '13 10:03

Ravi Karthik


People also ask

What is assembly GetExecutingAssembly ()?

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.

How do you access the assembly of a running application?

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.

What is System reflection assembly?

System. Reflection. Assembly. It defines an assembly, which is a reusable, versionable and self describing building block of a Common Language Runtime.


2 Answers

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().

like image 130
Mike Harder Avatar answered Sep 23 '22 07:09

Mike Harder


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.

like image 34
Arturo Martinez Avatar answered Sep 25 '22 07:09

Arturo Martinez