Skip to main content

Dynamic Assembly in C#

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

Popular Posts

SSAS: The Sort Order Specified For Distinct Count Records Is Incorrect.

Symptoms During a processing time of a cube that contains a distinct count measure, the process fails with the following error message: The sort order specified for distinct count records is incorrect Cause This is most likely caused by different sort order used on the data warehouse data set and the analysis service database data set. Resolution Modify the sort order of the data warehouse data set so that it will match with the analysis service database data set. Into the Depth  Navigate to the analysis database and start to process the desired database. When the processing begins, the Process progress window will pop up. Wait till the process gets failed. After the process failed, find the failing measure group and expand to the last node where you can see an SQL query. Double click on the query and view the details. This query gives you the exact order by the column which caused you this trouble.  Execute the query using the data warehouse datab...

Setup Azure AD B2C: Identity providers & Policies

This blog post will be the second part of the Setup Azure AD B2C blog series. From this blog post, we will be able to set up identity providers and policies to the Azure B2C AD. Identity providers An identity provider (abbreviated IdP or IDP ) is a system entity that creates, maintains, and manages identity information for principals while providing authentication services to relying applications within a federation or distributed network Azure AD B2C - Identity providers Azure supports many identities such as social, enterprise, or local account identities in B2C AAD. The following image shows some of the identity providers that currently B2C AAD support. As you can see AAD B2C Supports numerous identity providers. Except for Local account every other identity provider, you have to configure manually. Configure Social IDP In order to use social identity providers, we need to configure them first. Different identity providers use different ways to configure IDP. So ...

ASP.NET Core 3.1 - Setting up React app with Typescript

With the release of .NET Core 3.1, I have decided to migrate one of my .NET core 2.1 solutions which contain ASP.NET core API project, React Web project (ASP.NET core project with react typescript template) and .NET Core Library project.  So I started the migration with the Library and API projects. Based on my experience, I think it was not a smooth migration due to the vast number of breaking changes but I managed to up and run both projects. Lastly, I have started to migrate the React ASP.NET core project. It was chaotic but I managed to up and run the project. Thought it worked I got some issues here and there so I decided not to continue with the same project rather create a new ASP.NET Core 3.1 React TypeScript template project. When you are going to create a new project, Visual Studio provided you a list of templates where you can pick desired Even though we have a project template for ASP.NET Core with React JS, there is no direct project templ...