Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Assembly.GetAssembly(type) vs type.Assembly

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?

like image 397
bevacqua Avatar asked Oct 29 '25 03:10

bevacqua


1 Answers

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)

like image 57
Chris Sinclair Avatar answered Oct 30 '25 18:10

Chris Sinclair