As the title suggests, how do these two differentiate with each other? Are we safe to say they both the same? When is the best case where we choose one over the other? I just happened to come across it and I wasn't really sure. I hope someone can clear my doubts. Thanks in advance.
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.
If you know the assembly's file system path, you can call the static (C#) or Shared (Visual Basic) AssemblyName. GetAssemblyName method to get the fully qualified assembly name.
this.GetType()
gets the polymorphic type of the current instance, which may actually be a subclass of the class you're calling this.GetType()
from, and that subclass may be located in a different assembly.
Consider the following:
AssemblyA.dll:
public class Foo
{
public void PrintAssembly()
{
Console.WriteLine(this.GetType().Assembly.GetName());
Console.WriteLine(Assembly.GetExecutingAssembly().GetName());
}
}
AssemblyB.dll:
public class Bar : Foo
{
}
Now if you run the following code:
Bar b = new Bar();
b.PrintAssembly();
The result of the two ways of determining the assembly will not be the same; this.GetType().Assembly
will return AssemblyB (because the actual type of this
is Bar
), whereas Assembly.GetExecutingAssembly()
returns AssemblyA, because that's the assembly containing the Foo.PrintAssembly()
method.
The only time you can be certain that they refer to the same assembly is if the type containing the call to this.GetType()
is sealed.
One tells you the version of the Assembly the Type belongs to. The other tells you the version of the assembly that is currently executing. But you knew that already.
I believe you can safely assume that the executing assembly is always going to be the same as the assembly that 'this' is part of. At least I can't think of why it wouldn't be.
Whether you choose one or the other, for clarity sake, would be dependent upon whether you're looking for the assembly of the type, or the assembly that's executing. Let's say your dad and your boss are the same person... do you refer to him as your boss at the dinner table? Or do you introduce him to your girlfriend as your boss? Use the one that's going to make sense to the next person who reads your code.
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