What is the difference between this.GetType (). Assembly.GetName (). Version and Assembly.GetExecutingAssembly (). GetName (). Version?

As the name implies, how do these two differentiate with each other? Is it possible to say that they are both the same? When is the best case when we choose one by one? I just stumbled upon it, and I was not sure. Hope someone can resolve my doubts. Thanks in advance.

+6
source share
2 answers

this.GetType() gets the polymorphic type of the current instance, which can actually be a subclass of the class that you call this.GetType() , and this subclass can be located in another 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 methods for determining the assembly will not be the same; this.GetType().Assembly will return AssemblyB (since the actual type of this is Bar ), while Assembly.GetExecutingAssembly() returns AssemblyA because the assembly contains the Foo.PrintAssembly() method.

The only time you can be sure that they reference the same assembly is that the type containing the call to this.GetType() is sealed.

+12
source

One tells you the version of the Assembly to which the Type belongs. Another tells you the version of the assembly that is currently running. But you already knew that.

I believe that you can safely assume that the executing assembly will always be the same as the assembly of which 'this' is part. At least I canโ€™t think of why this will not happen.

If you have chosen one or the other, for clarity, it will depend on whether you are looking for a type assembly or an assembly to be performed. Say that your dad and your boss are the same person ... do you call him your boss at the dinner table? Or do you introduce him to your girlfriend as your boss? Use one that will make sense to the next person who reads your code.

+3
source

Source: https://habr.com/ru/post/901789/


All Articles