Static Assembly Vs Dynamic Assembly
Static Assemblies are those assemblies which are stored on the disk permanently as a file or set of files. Since these assemblies are stored in the disk, those are only loaded when CLR requests. These are the assemblies we are dealing with daily.Assemblies that I'm going to talk about today bit different. It completely opposite of the Static Assemblies. Those Assemblies are not stored on the disk before execution. When an application requires any type, which references from these assemblies, DOT NET will create these Assemblies at the runtime so that it will directly load into the memory.
Why is it important ?
Like I mentioned, this is not something we do very often. It is not all about how important it is. Personally, I think it is better to know this kind of hidden language features. More you play with this more you learn. I found cool stuff I can do with this. Hope it will be same for you as well. This is an old feature.How to use
class Program { static void Main(string[] args) { // Define fields needed with corresponding type var fields= new Dictionary<string, Type>() { { "Country", typeof(string) }, { "Address", typeof(string) }, { "Id", typeof(Guid) } }; // Create a new type in a dynamic assembly Type myAnonymousType = CreateNewType(fields); // Create an instance, type of newly defined anonymous type dynamic myAnonymousObj = Activator.CreateInstance(myAnonymousType); } public static Type CreateNewType(Dictionary<string, Type> fields) { // Let's start by creating a new assembly AssemblyName dynamicAssemblyName = new AssemblyName("MyAssembly"); AssemblyBuilder dynamicAssembly = AssemblyBuilder.DefineDynamicAssembly(dynamicAssemblyName, AssemblyBuilderAccess.Run); ModuleBuilder dynamicModule = dynamicAssembly.DefineDynamicModule("MyAssembly"); // Now let's build a new type TypeBuilder dynamicAnonymousType = dynamicModule.DefineType("myAnonymousType", TypeAttributes.Public); // Let's add some fields to the type. foreach (var field in fields) { FieldInfo dynField = dynamicAnonymousType.DefineField(field.Key, field.Value, FieldAttributes.Public); } // Return the type to the caller return dynamicAnonymousType.CreateType(); } }
Set some breakpoints and inspect variables. That will help you more.
May the force be with you!
Comments
Post a Comment