Learner
Learner

Reputation: 4751

Loading .NET 4.5.2 assembly in .NET 4 application, reflection & reference

It is allowed to load the .NET 4.5.2 assembly (using reflection) in the application whose exe is compiled using .NET 4 framework. However if I reference the same assembly in that application during development (added as any other assembly reference), build fails.

Why is it the case that thing which is not allowed during development is allowed at runtime using reflection?

Upvotes: 2

Views: 1223

Answers (1)

Rob
Rob

Reputation: 45799

Loading an assembly, or doing anything really, via Reflection is a "here there be dragons" scenario where you're assuming the risk, and reacting to, anything that goes wrong (such as an assembly that targets a later version of the framework than is available).

I only see Compiler warnings when referencing a project that targets a higher framework version:

The referenced project 'ProjectForNetFramework45' is targeting a higher framework version (4.6.1) than this project’s current target framework version (4.0). This may lead to build failures if types from assemblies outside this project’s target framework are used by any project in the dependency chain.

Rather than a build failure, until I actually attempt to call a method in the v4.5 assembly at which point the following pops up:

error CS0400: The type or namespace name 'ProjectForNetFramework45' could not be found in the global namespace (are you missing an assembly reference?)

The 4.5 version of the .net Framework is an "in-place update" rather than a new version, see the notes in this Microsoft blog post about Compatibility of .NET Framework 4.5:

.NET Framework 4.5 is an in-place update that replaces .NET Framework 4 (rather than a side-by-side installation). Our goal is for .NET 4.5 to be fully backward compatible with applications built for .NET 4 (.NET 3.5 and .NET 4.5 will be side-by-side). We’ll talk about the compatibility story for .NET 3.5 in a later post. One of the first things you’ll notice about .NET 4.5 is the version number (4.0.30319) is the same as .NET 4; this is the practice used by other in-place updates.

This means that, rather than being a different version of the runtime (i.e. the JIT, Garabage Collector, etc,.. although these do change!), a newer framework will likely add new classes, interfaces and methods to existing classes giving a wider API to work against. This is one of the things that "netstandard" is an attempt to add clarity to.

Upvotes: 1

Related Questions