Reputation: 48526
I wanted to know what are the benefits, if any, to calling either of these methods, and why?
Are they functionally equivalent, or should I always be choosing one over the other?
Upvotes: 4
Views: 2347
Reputation: 23218
AFAIK they're functionally equivalent, however Assembly.GetAssembly(Type) is not available in the core-clr (Silverlight and the like)
You would get different errors based on whether or not your Type
is null. Type.Assembly
will throw a NullReferenceException (naturally) whereas Assembly.GetAssembly(Type)
would throw an ArgumentNullException. Based on your code you might prefer one or the other.
EDIT: Looking at the source, for Assembly.GetAssembly
:
public static Assembly GetAssembly(Type type)
{
if (type == null)
throw new ArgumentNullException("type");
Contract.EndContractBlock();
Module m = type.Module;
if (m == null)
return null;
else
return m.Assembly;
}
Whereas System.Type.Assembly
:
public abstract Assembly Assembly {
get;
}
If I recall correctly, the System.Type for runtime types are their own subclasses (or something like that) So I guess each one maybe overrides and simply directly returns an assembly reference. Beyond that, I don't think there's any significant difference for you to worry about with your code beyond null handling which is up to you. (Or if you're running the Core-CLR in which case you don't have Assembly.GetAssembly anyway so you must use Type.Assembly)
Upvotes: 4
Reputation: 180878
From the documentation for Type.Assembly
If the current
Type
object represents a constructed generic type, this property returns the assembly that contains the generic type definition.For example, suppose you create an assembly named
MyGenerics.dll
that contains the generic type definitionMyGenericStack<T>
. If you create an instance ofMyGenericStack<int>
in another assembly, the Assembly property for the constructed type returns an Assembly object that representsMyGenerics.dll
From the documentation for Assembly.GetAssembly:
In order to call this method, you must have a
Type
object, which means that the assembly in which the class is defined must already be loaded.
Upvotes: 0