woodykiddy
woodykiddy

Reputation: 6455

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

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.

Upvotes: 9

Views: 4384

Answers (2)

Sven
Sven

Reputation: 22703

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.

Upvotes: 15

Brandon Moore
Brandon Moore

Reputation: 8790

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.

Upvotes: 4

Related Questions