{"id":73515,"date":"2022-08-23T08:00:49","date_gmt":"2022-08-23T06:00:49","guid":{"rendered":"https:\/\/drafts.code-maze.com\/?p=73515"},"modified":"2022-08-23T08:30:48","modified_gmt":"2022-08-23T06:30:48","slug":"create-class-dynamically-csharp","status":"publish","type":"post","link":"https:\/\/code-maze.com\/create-class-dynamically-csharp\/","title":{"rendered":"How to Create a Class Dynamically in C#?"},"content":{"rendered":"<p>In this article, we are going to learn how to create a class dynamically in C#. Thanks to the introduction of the <a href=\"https:\/\/code-maze.com\/dynamic-type-csharp\/\" target=\"_blank\" rel=\"noopener\">dynamic type<\/a> in C# 4, working with dynamic classes has become easier, but we shouldn&#8217;t abuse it. Dynamic classes are very powerful, but they bring a substantial overhead as well.<\/p>\n<div style=\"padding: 20px; border-left: 5px #dc2323 solid; display: block; margin-bottom: 20px; box-shadow: 1px 1px 5px 0px lightgrey;\">To download the source code for this article, you can visit our <a href=\"https:\/\/github.com\/CodeMazeBlog\/CodeMazeGuides\/tree\/main\/csharp-advanced-topics\/DynamicallyCreateClass\" target=\"_blank\" rel=\"nofollow noopener\">GitHub repository<\/a>.<\/div>\n<p>Let&#8217;s start.<\/p>\n<h2>Why Do We Need Dynamic Classes?<\/h2>\n<p>Before looking at the code, let&#8217;s imagine a scenario where using a dynamic class is a reasonable choice. We need to aggregate data coming from several weather stations. The problem is that each station returns this data as JSON, each with a different schema. This means that the first weather station could return the temperature as &#8220;Temperature1&#8221;, the second one as &#8220;Temperature2&#8221;, and so on.<\/p>\n<p>We might not want to create a data class for each weather station response, so what is it that we can do in this case?\u00a0<\/p>\n<h2>How to Create a Class Dynamically With ExpandoObject<\/h2>\n<p><code>ExpandoObject<\/code> is part of the <code>System.Dynamic<\/code> namespace and allows us to add\/remove properties to it at runtime. Creating an instance of the <code>ExpandoObject<\/code> is as simple as:<\/p>\n<p><code class=\"EnlighterJSRAW\" data-enlighter-language=\"csharp\">dynamic expando = new ExpandoObject();<\/code><\/p>\n<p>Then, if we need to add a new property to this instance, it is sufficient to initialize it using the dot-notation:<\/p>\n<p><code class=\"EnlighterJSRAW\" data-enlighter-language=\"csharp\">expando.MyNewProperty = \"dynamic property\"<\/code><\/p>\n<p>In our example, we have one of the weather stations that returns this JSON object:<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"json\">{ \r\n    \"Temperature1\": 10.5, \r\n    \"Humidity1\": 50\r\n}<\/pre>\n<p>How can we create an <code>ExpandoObject<\/code> from this JSON string? We have 2 options: <code>Newtonsoft.Json<\/code> or <code>System.Text.Json<\/code>. While the second one should guarantee better performances, it does not yet provide full support for dynamic objects. With <code>System.Text.Json<\/code>, even if we specify <code>ExpandoObject<\/code> to be the deserialization type, each property is wrapped in a <code>JsonElement<\/code>:<\/p>\n<p><code class=\"EnlighterJSRAW\" data-enlighter-language=\"csharp\">dynamic expando = JsonSerializer.Deserialize&lt;ExpandoObject&gt;(jsonWeather);<\/code><\/p>\n<p>If we try to access <code>expando.Temperature1<\/code> we get a <code>JsonElement<\/code> representing the value <code>10.5<\/code>. On the other hand, with <code>Newtonsoft.Json<\/code>, properties are deserialized as expected:\u00a0<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"csharp\">var expandoConverter = new ExpandoObjectConverter();\r\ndynamic expando = JsonConvert.DeserializeObject&lt;ExpandoObject&gt;(\r\n    json, expandoConverter);<\/pre>\n<p><code>expando.Temperature1<\/code> and <code>expando.Humidity1<\/code> return 10.5 and 50, respectively.<\/p>\n<p>We can also simulate a method call by assigning a lambda to a new property:<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"csharp\">var toCsvFormatter = (dynamic thisObj) =&gt; \r\n    () =&gt; \r\n    {\r\n        StringBuilder sb = new StringBuilder();\r\n\r\n        foreach (var prop in (IDictionary&lt;String, Object&gt;)thisObj)\r\n            if (prop.Key != \"Format\")\r\n                sb.Append($\"{prop.Value},\");\r\n\r\n        sb.Remove(sb.Length - 1, 1);\r\n\r\n        return sb.ToString();\r\n    };\r\n\r\nexpando.Format = toCsvFormatter(expando);<\/pre>\n<p><code>toCsvFormatter(expando)<\/code> is a partial application of the <code>toCsvFormatter<\/code> lambda. This is convenient because we cannot access <code>this<\/code>, which is <code>expando<\/code>, directly from inside the lambda. The only way to access it is to pass it as an argument to the lambda itself. Instead of passing <code>expando<\/code> every time we need to call <code>Format()<\/code>, we do it at initialization time.<\/p>\n<p>We call <code>Format()<\/code> the same way we call a method from a statically compiled class. Starting from the previous expando initialization:<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"csharp\">var formattedExpando = expando.Format();\r\nAssert.AreEqual(\"10.5,50\", formattedExpando);<\/pre>\n<p>In the lambda body, we are looping over each property of <code>expando<\/code>. The <code>ExpandoObject<\/code> implements the <code><span class=\"pl-en\">IDictionary<\/span>&lt;<span class=\"pl-k\">string<\/span>, <span class=\"pl-k\">object<\/span>&gt;<\/code> interface, which allows us to enumerate properties as key-value pairs or to remove one with:<\/p>\n<p><code class=\"EnlighterJSRAW\" data-enlighter-language=\"csharp\">((IDictionary&lt;string, Object&gt;)expando).Remove(\"Temperature1\");<\/code><\/p>\n<p>Another interesting feature of the <code>ExpandoObject<\/code> is the possibility to attach an event handler when any dynamic property changes. Let&#8217;s create a class that aggregates data coming from weather stations:<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"csharp\">public class WeatherAggregator\r\n{\r\n    public WeatherAggregator(dynamic weatherExpando1, dynamic weatherExpando2, dynamic weatherExpando3)\r\n    {\r\n        foreach (var weatherExp in new dynamic[] { weatherExpando1, weatherExpando2, weatherExpando3 })\r\n        {\r\n            ((INotifyPropertyChanged)weatherExp).PropertyChanged += new PropertyChangedEventHandler(\r\n                (sender, e) =&gt; \r\n                {\r\n                    ComputeAggregatedWeather();\r\n                }\r\n            );\r\n        }\r\n\r\n        ComputeAggregatedWeather();\r\n    }\r\n\r\n    private void ComputeAggregatedWeather()\r\n    {\r\n        \/\/ ...\r\n    }\r\n}<\/pre>\n<p>Each time we change a property (like temperature or humidity) of any expando, we should also recompute the aggregation operations. We can do it by leveraging the <code>INotifyPropertyChanged<\/code> interface implemented by <code>ExpandoObject<\/code>.<\/p>\n<p>This works by adding an event handler of type <code>PropertyChangedEventHandler<\/code> to the <code>PropertyChanged<\/code> member of all the expando objects. In this event handler, we recompute the aggregated data by calling <code>ComputeAggregatedWeather()<\/code>.<\/p>\n<h3>Advantages and Disadvantages of ExpandoObject<\/h3>\n<p><code>ExpandoObject<\/code> <strong>is very simple to use and it is probably the best way to bypass static type checking<\/strong>. This is a huge advantage, that should usually make it our favorite way to work with dynamic classes. However, we might need a custom dynamic binding logic, which is different from the one implemented in the <code>ExpandoObject<\/code>.<\/p>\n<p>Let&#8217;s find out how to customize the dynamic binding behavior.<\/p>\n<h2>How to Create a Class Dynamically With DynamicObject<\/h2>\n<p><code>DynamicObject<\/code> is a class in the <code>System.Dynamic<\/code> namespace, but we have to inherit it because of the constructor protection level (protected). Let&#8217;s see how we can do that by solving the weather stations problem again. We are going to wrap the dynamic object created by the JSON deserialization with a <code>DynamicWeatherData<\/code> object:<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"csharp\">dynamic weatherObj = new DynamicWeatherData(\r\n    JsonSerializer.Deserialize&lt;JsonObject&gt;(json)\r\n);<\/pre>\n<p>In this case, we have used <code>System.Text.Json<\/code>, but it is possible with the Json.NET library as well. With Json.NET, instead of deserializing into a <code>JsonObject<\/code>, we could have used a <code>JObject<\/code>, which supports DLR. We will not cover the details of the serialization of dynamic objects, but we have written an article on how to <a href=\"https:\/\/code-maze.com\/csharp-deserialize-json-into-dynamic-object\/\" target=\"_blank\" rel=\"noopener\">deserialize JSON into a dynamic object<\/a>. This is how we can implement a basic version of <code>DynamicWeatherData<\/code>:<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"csharp\">public class DynamicWeatherData : DynamicObject\r\n{\r\n    JsonObject _weatherData;\r\n\r\n    public DynamicWeatherData(JsonObject weatherData)\r\n    {\r\n        _weatherData = weatherData;\r\n    }\r\n\r\n    public override bool TrySetMember(SetMemberBinder binder, object? value)\r\n    {\r\n        if (!_weatherData.ContainsKey(binder.Name))\r\n            return false;\r\n\r\n        _weatherData[binder.Name] = value == null ? null : JsonValue.Create(value);\r\n\r\n        return true;\r\n    }\r\n\r\n    public override bool TryGetMember(GetMemberBinder binder, out object? result)\r\n    {\r\n        if (!_weatherData.ContainsKey(binder.Name))\r\n        {\r\n            result = null;\r\n            return false;\r\n        }\r\n\r\n        result = _weatherData[binder.Name]?.AsValue();\r\n        return true;\r\n    }\r\n}<\/pre>\n<p>The first thing we see is that we completely lost the simplicity of <code>ExpandoObject<\/code>. Now we have to implement the class behavior, starting with where and how to store the members of the class itself.\u00a0We have chosen <code>JsonObject<\/code> as data storage, but properties are dynamically accessed through <code>TryGetMember()<\/code> and <code>TrySetMember()<\/code>:<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"csharp\">weatherObj.Temperature1 = 10;\r\nAssert.IsTrue(weatherObj.Temperature1.GetType().IsAssignableTo(typeof(JsonValue)));\r\nAssert.AreEqual(10, (int)weatherObj.Temperature1);<\/pre>\n<p>When we assign 10 to <code>weatherObj.Temperature1<\/code>, <code>TrySetMember()<\/code> is called. In this case, <code>binder.Name<\/code> is equal to <code>\"Temperature1\"<\/code> and <code>value<\/code> is 10. If the property name already exists in <code>_weatherData<\/code>, then we store the new value as a <code>JsonValue<\/code> and return <code>true<\/code>.<\/p>\n<p>When we try to get <code>weatherObj.Temperature1<\/code> in the assertions, <code>TryGetMember()<\/code> is called. <code>binder.Name<\/code> is equal to <code>\"Temperature1\"<\/code>, but we must initialize <code>result<\/code> before returning. If the property name already exists in <code>_weatherData<\/code>, then we return the stored value as a <code>JsonValue<\/code> and return <code>true<\/code>. The explicit cast to <code>int<\/code> is necessary because the <code>result<\/code> type is <code>JsonValue<\/code>.<\/p>\n<p>Both <code>TryGetMember()<\/code> and <code>TrySetMember()<\/code> return a boolean value, which represents the success or failure of the method execution. In case of failure (<code>false<\/code>), the runtime binder usually throws an exception.<\/p>\n<p>So far, there is no reason to wrap a <code>JsonObject<\/code> with a <code>DynamicObject<\/code> because we are just overcomplicating the design. After all, what have we gained over the solution with <code>ExpandoObject<\/code>? We should probably not adopt this approach when we can achieve the same result with <code>ExpandoObject<\/code>.<\/p>\n<p>The beauty of <code>DynamicObject<\/code> is that we can customize many other aspects of our class. The first one we are going to see is <code>TryInvokeMember()<\/code>:<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"csharp\">public override bool TryInvokeMember(InvokeMemberBinder binder, object?[]? args, out object? result)\r\n{\r\n    if (binder.Name == \"Format\" &amp;&amp; args?.Length == 0)\r\n    {\r\n        var (temperature, humidity) = GetProperties();\r\n\r\n        result = $\"{temperature},{humidity}\";\r\n        return true;\r\n    }\r\n    else\r\n    {\r\n        result = null;\r\n        return false;\r\n    }\r\n}\r\n\r\nprivate (double, int) GetProperties()\r\n{\r\n    var temperatureAttr = _weatherData\r\n        .First(kv =&gt; kv.Key.StartsWith(\"Temperature\"))\r\n        .Value!.GetValue&lt;double&gt;();\r\n    var humidityAttr = _weatherData\r\n        .First(kv =&gt; kv.Key.StartsWith(\"Humidity\"))\r\n        .Value!.GetValue&lt;int&gt;();\r\n\r\n    return (temperatureAttr, humidityAttr);\r\n}<\/pre>\n<p><code>binder.Name<\/code> contains the method name we are trying to call, <code>args<\/code> are the arguments provided to the method. The advantage we have here over the <code>ExpandoObject<\/code> solution is that we have direct access to the class methods. The only supported method in the example is <code>Format()<\/code>, which we can call with:<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"csharp\">var formattedWeather = weatherObj.Format();\r\nAssert.AreEqual(\"10.5,50\", formattedWeather);<\/pre>\n<p>What if we wanted to cast our <code>dynamic<\/code> object to a data class, like <code>WeatherData<\/code>:<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"csharp\">public class WeatherData \r\n{\r\n    public WeatherData(double temperature, int humidity) \r\n    {\r\n        this.Temperature = temperature;\r\n        this.Humidity = humidity;\r\n    }\r\n\r\n    public double Temperature { get; init; }\r\n    public int Humidity { get; init; }\r\n}<\/pre>\n<p>With an <code>ExpandoObject<\/code>, we would need to create a method that cast the dynamic object to the data class involved. This is not a real problem, but we would lose the possibility to use explicit\/implicit casting. Instead, to support the casting operator in <code>DynamicWeatherData<\/code>, we just need to override <code>TryConvert()<\/code>:\u00a0<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"csharp\">public override bool TryConvert(ConvertBinder binder, out object? result)\r\n{\r\n    if (binder.Type.Equals(typeof(WeatherData)))\r\n    {\r\n        var (temperature, humidity) = GetProperties();\r\n\r\n        result = new WeatherData(temperature, humidity);\r\n        return true;\r\n    }\r\n    else \r\n    {\r\n        result = null;\r\n        return false;\r\n    }\r\n}<\/pre>\n<p><code>binder<\/code> contains the target type, which can come from implicit or explicit casting. This means that this is perfectly valid:<\/p>\n<p><code class=\"EnlighterJSRAW\" data-enlighter-language=\"csharp\">WeatherData castObj = weatherObj;<\/code><\/p>\n<p>Where the type of <code>weatherObj<\/code> is <code>DynamicWeatherData<\/code>.<\/p>\n<p>We have seen just a few possible methods we can override to customize the dynamic behavior of our class. Was this the right way to solve the initial problem?<\/p>\n<h3>Advantages and Disadvantages of DynamicObject<\/h3>\n<p><code>ExpandoObject<\/code> <strong>and <\/strong><code>DynamicObject<\/code> <strong>have one thing in common: they both implement <\/strong><code>IDynamicMetaObjectProvider<\/code><strong>. This interface is responsible for DLR support<\/strong>. The difference is that <code>DynamicObject<\/code> is much more flexible than <code>ExpandoObject<\/code>, which is limited to what we have shown previously. In the examples we proposed, <code>DynamicObject<\/code> was unnecessary and the benefits we obtained didn&#8217;t pay off the implementation costs.<\/p>\n<p>For these reasons, before opting for <code>DynamicObject<\/code>, we should try to solve the problem with <code>ExpandoObject<\/code>.<\/p>\n<p>And what if <code>DynamicObject<\/code> isn&#8217;t good enough?<\/p>\n<h2>Create a Class Dynamically in C# With Roslyn<\/h2>\n<p>Roslyn, the .NET compiler, has some public APIs that we can use to compile source code at runtime. Finding a reasonable use case for them is probably more difficult than using them. It might be convenient if we wanted to execute a piece of code on a remote device.<\/p>\n<p>We are not going to cover this topic extensively here because it is very complex. <strong>We have added a simple example in the GitHub repository<\/strong> (see <code>CSharpRuntimeCompilerUnitTest.cs<\/code>), but it is just the tip of the iceberg. If we don&#8217;t have a choice and we are left with this solution, our advice is to start from <a href=\"https:\/\/weblog.west-wind.com\/posts\/2022\/Jun\/07\/Runtime-CSharp-Code-Compilation-Revisited-for-Roslyn\" target=\"_blank\" rel=\"nofollow noopener\">this article<\/a>.<\/p>\n<h2>Conclusion<\/h2>\n<p>Creating a class dynamically in C# <strong>isn&#8217;t cheap at all in terms of performance<\/strong>. Moreover, <strong>we lose static type-checking and the risk of introducing a bug is higher<\/strong>. Typically, we should give priority to ExpandoObject because easier to use. We have also seen the approach based on DynamicObject, which is harder to maintain but more flexible than ExpandoObject.<\/p>\n","protected":false},"excerpt":{"rendered":"<p>In this article, we are going to learn how to create a class dynamically in C#. Thanks to the introduction of the dynamic type in C# 4, working with dynamic classes has become easier, but we shouldn&#8217;t abuse it. Dynamic classes are very powerful, but they bring a substantial overhead as well. Let&#8217;s start. Why [&hellip;]<\/p>\n","protected":false},"author":6,"featured_media":62189,"comment_status":"open","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":{"_et_pb_use_builder":"","_et_pb_old_content":"","_et_gb_content_width":"","footnotes":""},"categories":[12],"tags":[10,324,471,1405,1404,1406],"class_list":["post-73515","post","type-post","status-publish","format-standard","has-post-thumbnail","hentry","category-csharp","tag-net","tag-classes","tag-dynamic","tag-dynamicobject","tag-expandoobject","tag-roslyn","et-has-post-format-content","et_post_format-et-post-format-standard"],"yoast_head":"<!-- This site is optimized with the Yoast SEO plugin v24.7 - https:\/\/yoast.com\/wordpress\/plugins\/seo\/ -->\n<title>How to Create a Class Dynamically in C#? - Code Maze<\/title>\n<meta name=\"description\" content=\"Creating a class dynamically in C# isn&#039;t cheap in terms of performance. We lose static type-checking and the risk of having bugs is higher.\" \/>\n<meta name=\"robots\" content=\"index, follow, max-snippet:-1, max-image-preview:large, max-video-preview:-1\" \/>\n<link rel=\"canonical\" href=\"https:\/\/code-maze.com\/create-class-dynamically-csharp\/\" \/>\n<meta property=\"og:locale\" content=\"en_US\" \/>\n<meta property=\"og:type\" content=\"article\" \/>\n<meta property=\"og:title\" content=\"How to Create a Class Dynamically in C#? - Code Maze\" \/>\n<meta property=\"og:description\" content=\"Creating a class dynamically in C# isn&#039;t cheap in terms of performance. We lose static type-checking and the risk of having bugs is higher.\" \/>\n<meta property=\"og:url\" content=\"https:\/\/code-maze.com\/create-class-dynamically-csharp\/\" \/>\n<meta property=\"og:site_name\" content=\"Code Maze\" \/>\n<meta property=\"article:published_time\" content=\"2022-08-23T06:00:49+00:00\" \/>\n<meta property=\"article:modified_time\" content=\"2022-08-23T06:30:48+00:00\" \/>\n<meta property=\"og:image\" content=\"https:\/\/code-maze.com\/wp-content\/uploads\/2021\/12\/social-csharp.png\" \/>\n\t<meta property=\"og:image:width\" content=\"1100\" \/>\n\t<meta property=\"og:image:height\" content=\"620\" \/>\n\t<meta property=\"og:image:type\" content=\"image\/png\" \/>\n<meta name=\"author\" content=\"Code Maze\" \/>\n<meta name=\"twitter:card\" content=\"summary_large_image\" \/>\n<meta name=\"twitter:creator\" content=\"@https:\/\/twitter.com\/CodeMazeBlog\" \/>\n<meta name=\"twitter:site\" content=\"@CodeMazeBlog\" \/>\n<meta name=\"twitter:label1\" content=\"Written by\" \/>\n\t<meta name=\"twitter:data1\" content=\"Code Maze\" \/>\n\t<meta name=\"twitter:label2\" content=\"Est. reading time\" \/>\n\t<meta name=\"twitter:data2\" content=\"8 minutes\" \/>\n<script type=\"application\/ld+json\" class=\"yoast-schema-graph\">{\"@context\":\"https:\/\/schema.org\",\"@graph\":[{\"@type\":[\"Article\",\"BlogPosting\"],\"@id\":\"https:\/\/code-maze.com\/create-class-dynamically-csharp\/#article\",\"isPartOf\":{\"@id\":\"https:\/\/code-maze.com\/create-class-dynamically-csharp\/\"},\"author\":{\"name\":\"Code Maze\",\"@id\":\"https:\/\/code-maze.com\/#\/schema\/person\/09d29b223012c8e94a68ba62861d0b04\"},\"headline\":\"How to Create a Class Dynamically in C#?\",\"datePublished\":\"2022-08-23T06:00:49+00:00\",\"dateModified\":\"2022-08-23T06:30:48+00:00\",\"mainEntityOfPage\":{\"@id\":\"https:\/\/code-maze.com\/create-class-dynamically-csharp\/\"},\"wordCount\":1348,\"commentCount\":0,\"publisher\":{\"@id\":\"https:\/\/code-maze.com\/#organization\"},\"image\":{\"@id\":\"https:\/\/code-maze.com\/create-class-dynamically-csharp\/#primaryimage\"},\"thumbnailUrl\":\"https:\/\/code-maze.com\/wp-content\/uploads\/2021\/12\/social-csharp.png\",\"keywords\":[\".NET\",\"Classes\",\"Dynamic\",\"DynamicObject\",\"ExpandoObject\",\"Roslyn\"],\"articleSection\":[\"C#\"],\"inLanguage\":\"en-US\",\"potentialAction\":[{\"@type\":\"CommentAction\",\"name\":\"Comment\",\"target\":[\"https:\/\/code-maze.com\/create-class-dynamically-csharp\/#respond\"]}]},{\"@type\":\"WebPage\",\"@id\":\"https:\/\/code-maze.com\/create-class-dynamically-csharp\/\",\"url\":\"https:\/\/code-maze.com\/create-class-dynamically-csharp\/\",\"name\":\"How to Create a Class Dynamically in C#? - Code Maze\",\"isPartOf\":{\"@id\":\"https:\/\/code-maze.com\/#website\"},\"primaryImageOfPage\":{\"@id\":\"https:\/\/code-maze.com\/create-class-dynamically-csharp\/#primaryimage\"},\"image\":{\"@id\":\"https:\/\/code-maze.com\/create-class-dynamically-csharp\/#primaryimage\"},\"thumbnailUrl\":\"https:\/\/code-maze.com\/wp-content\/uploads\/2021\/12\/social-csharp.png\",\"datePublished\":\"2022-08-23T06:00:49+00:00\",\"dateModified\":\"2022-08-23T06:30:48+00:00\",\"description\":\"Creating a class dynamically in C# isn't cheap in terms of performance. We lose static type-checking and the risk of having bugs is higher.\",\"breadcrumb\":{\"@id\":\"https:\/\/code-maze.com\/create-class-dynamically-csharp\/#breadcrumb\"},\"inLanguage\":\"en-US\",\"potentialAction\":[{\"@type\":\"ReadAction\",\"target\":[\"https:\/\/code-maze.com\/create-class-dynamically-csharp\/\"]}]},{\"@type\":\"ImageObject\",\"inLanguage\":\"en-US\",\"@id\":\"https:\/\/code-maze.com\/create-class-dynamically-csharp\/#primaryimage\",\"url\":\"https:\/\/code-maze.com\/wp-content\/uploads\/2021\/12\/social-csharp.png\",\"contentUrl\":\"https:\/\/code-maze.com\/wp-content\/uploads\/2021\/12\/social-csharp.png\",\"width\":1100,\"height\":620,\"caption\":\"C# Development\"},{\"@type\":\"BreadcrumbList\",\"@id\":\"https:\/\/code-maze.com\/create-class-dynamically-csharp\/#breadcrumb\",\"itemListElement\":[{\"@type\":\"ListItem\",\"position\":1,\"name\":\"Home\",\"item\":\"https:\/\/code-maze.com\/\"},{\"@type\":\"ListItem\",\"position\":2,\"name\":\"How to Create a Class Dynamically in C#?\"}]},{\"@type\":\"WebSite\",\"@id\":\"https:\/\/code-maze.com\/#website\",\"url\":\"https:\/\/code-maze.com\/\",\"name\":\"Code Maze\",\"description\":\"Learn. Code. Succeed.\",\"publisher\":{\"@id\":\"https:\/\/code-maze.com\/#organization\"},\"potentialAction\":[{\"@type\":\"SearchAction\",\"target\":{\"@type\":\"EntryPoint\",\"urlTemplate\":\"https:\/\/code-maze.com\/?s={search_term_string}\"},\"query-input\":{\"@type\":\"PropertyValueSpecification\",\"valueRequired\":true,\"valueName\":\"search_term_string\"}}],\"inLanguage\":\"en-US\"},{\"@type\":\"Organization\",\"@id\":\"https:\/\/code-maze.com\/#organization\",\"name\":\"Code Maze\",\"url\":\"https:\/\/code-maze.com\/\",\"logo\":{\"@type\":\"ImageObject\",\"inLanguage\":\"en-US\",\"@id\":\"https:\/\/code-maze.com\/#\/schema\/logo\/image\/\",\"url\":\"https:\/\/code-maze.com\/wp-content\/uploads\/2020\/01\/Code-Maze-Only-Logo-Transparent-HRez.png\",\"contentUrl\":\"https:\/\/code-maze.com\/wp-content\/uploads\/2020\/01\/Code-Maze-Only-Logo-Transparent-HRez.png\",\"width\":3511,\"height\":3510,\"caption\":\"Code Maze\"},\"image\":{\"@id\":\"https:\/\/code-maze.com\/#\/schema\/logo\/image\/\"},\"sameAs\":[\"https:\/\/x.com\/CodeMazeBlog\"]},{\"@type\":\"Person\",\"@id\":\"https:\/\/code-maze.com\/#\/schema\/person\/09d29b223012c8e94a68ba62861d0b04\",\"name\":\"Code Maze\",\"image\":{\"@type\":\"ImageObject\",\"inLanguage\":\"en-US\",\"@id\":\"https:\/\/code-maze.com\/#\/schema\/person\/image\/\",\"url\":\"https:\/\/code-maze.com\/wp-content\/uploads\/2020\/01\/Code-Maze-Only-Logo-Transparent-HRez-150x150.png\",\"contentUrl\":\"https:\/\/code-maze.com\/wp-content\/uploads\/2020\/01\/Code-Maze-Only-Logo-Transparent-HRez-150x150.png\",\"caption\":\"Code Maze\"},\"description\":\"This is the standard author on the site. Most articles are published by individual authors, with their profiles, but when several authors have contributed, we publish collectively as a part of this profile.\",\"sameAs\":[\"https:\/\/www.linkedin.com\/company\/codemaze\/\",\"https:\/\/x.com\/https:\/\/twitter.com\/CodeMazeBlog\"],\"url\":\"https:\/\/code-maze.com\/author\/codemazecontributor\/\"}]}<\/script>\n<!-- \/ Yoast SEO plugin. -->","yoast_head_json":{"title":"How to Create a Class Dynamically in C#? - Code Maze","description":"Creating a class dynamically in C# isn't cheap in terms of performance. We lose static type-checking and the risk of having bugs is higher.","robots":{"index":"index","follow":"follow","max-snippet":"max-snippet:-1","max-image-preview":"max-image-preview:large","max-video-preview":"max-video-preview:-1"},"canonical":"https:\/\/code-maze.com\/create-class-dynamically-csharp\/","og_locale":"en_US","og_type":"article","og_title":"How to Create a Class Dynamically in C#? - Code Maze","og_description":"Creating a class dynamically in C# isn't cheap in terms of performance. We lose static type-checking and the risk of having bugs is higher.","og_url":"https:\/\/code-maze.com\/create-class-dynamically-csharp\/","og_site_name":"Code Maze","article_published_time":"2022-08-23T06:00:49+00:00","article_modified_time":"2022-08-23T06:30:48+00:00","og_image":[{"width":1100,"height":620,"url":"https:\/\/code-maze.com\/wp-content\/uploads\/2021\/12\/social-csharp.png","type":"image\/png"}],"author":"Code Maze","twitter_card":"summary_large_image","twitter_creator":"@https:\/\/twitter.com\/CodeMazeBlog","twitter_site":"@CodeMazeBlog","twitter_misc":{"Written by":"Code Maze","Est. reading time":"8 minutes"},"schema":{"@context":"https:\/\/schema.org","@graph":[{"@type":["Article","BlogPosting"],"@id":"https:\/\/code-maze.com\/create-class-dynamically-csharp\/#article","isPartOf":{"@id":"https:\/\/code-maze.com\/create-class-dynamically-csharp\/"},"author":{"name":"Code Maze","@id":"https:\/\/code-maze.com\/#\/schema\/person\/09d29b223012c8e94a68ba62861d0b04"},"headline":"How to Create a Class Dynamically in C#?","datePublished":"2022-08-23T06:00:49+00:00","dateModified":"2022-08-23T06:30:48+00:00","mainEntityOfPage":{"@id":"https:\/\/code-maze.com\/create-class-dynamically-csharp\/"},"wordCount":1348,"commentCount":0,"publisher":{"@id":"https:\/\/code-maze.com\/#organization"},"image":{"@id":"https:\/\/code-maze.com\/create-class-dynamically-csharp\/#primaryimage"},"thumbnailUrl":"https:\/\/code-maze.com\/wp-content\/uploads\/2021\/12\/social-csharp.png","keywords":[".NET","Classes","Dynamic","DynamicObject","ExpandoObject","Roslyn"],"articleSection":["C#"],"inLanguage":"en-US","potentialAction":[{"@type":"CommentAction","name":"Comment","target":["https:\/\/code-maze.com\/create-class-dynamically-csharp\/#respond"]}]},{"@type":"WebPage","@id":"https:\/\/code-maze.com\/create-class-dynamically-csharp\/","url":"https:\/\/code-maze.com\/create-class-dynamically-csharp\/","name":"How to Create a Class Dynamically in C#? - Code Maze","isPartOf":{"@id":"https:\/\/code-maze.com\/#website"},"primaryImageOfPage":{"@id":"https:\/\/code-maze.com\/create-class-dynamically-csharp\/#primaryimage"},"image":{"@id":"https:\/\/code-maze.com\/create-class-dynamically-csharp\/#primaryimage"},"thumbnailUrl":"https:\/\/code-maze.com\/wp-content\/uploads\/2021\/12\/social-csharp.png","datePublished":"2022-08-23T06:00:49+00:00","dateModified":"2022-08-23T06:30:48+00:00","description":"Creating a class dynamically in C# isn't cheap in terms of performance. We lose static type-checking and the risk of having bugs is higher.","breadcrumb":{"@id":"https:\/\/code-maze.com\/create-class-dynamically-csharp\/#breadcrumb"},"inLanguage":"en-US","potentialAction":[{"@type":"ReadAction","target":["https:\/\/code-maze.com\/create-class-dynamically-csharp\/"]}]},{"@type":"ImageObject","inLanguage":"en-US","@id":"https:\/\/code-maze.com\/create-class-dynamically-csharp\/#primaryimage","url":"https:\/\/code-maze.com\/wp-content\/uploads\/2021\/12\/social-csharp.png","contentUrl":"https:\/\/code-maze.com\/wp-content\/uploads\/2021\/12\/social-csharp.png","width":1100,"height":620,"caption":"C# Development"},{"@type":"BreadcrumbList","@id":"https:\/\/code-maze.com\/create-class-dynamically-csharp\/#breadcrumb","itemListElement":[{"@type":"ListItem","position":1,"name":"Home","item":"https:\/\/code-maze.com\/"},{"@type":"ListItem","position":2,"name":"How to Create a Class Dynamically in C#?"}]},{"@type":"WebSite","@id":"https:\/\/code-maze.com\/#website","url":"https:\/\/code-maze.com\/","name":"Code Maze","description":"Learn. Code. Succeed.","publisher":{"@id":"https:\/\/code-maze.com\/#organization"},"potentialAction":[{"@type":"SearchAction","target":{"@type":"EntryPoint","urlTemplate":"https:\/\/code-maze.com\/?s={search_term_string}"},"query-input":{"@type":"PropertyValueSpecification","valueRequired":true,"valueName":"search_term_string"}}],"inLanguage":"en-US"},{"@type":"Organization","@id":"https:\/\/code-maze.com\/#organization","name":"Code Maze","url":"https:\/\/code-maze.com\/","logo":{"@type":"ImageObject","inLanguage":"en-US","@id":"https:\/\/code-maze.com\/#\/schema\/logo\/image\/","url":"https:\/\/code-maze.com\/wp-content\/uploads\/2020\/01\/Code-Maze-Only-Logo-Transparent-HRez.png","contentUrl":"https:\/\/code-maze.com\/wp-content\/uploads\/2020\/01\/Code-Maze-Only-Logo-Transparent-HRez.png","width":3511,"height":3510,"caption":"Code Maze"},"image":{"@id":"https:\/\/code-maze.com\/#\/schema\/logo\/image\/"},"sameAs":["https:\/\/x.com\/CodeMazeBlog"]},{"@type":"Person","@id":"https:\/\/code-maze.com\/#\/schema\/person\/09d29b223012c8e94a68ba62861d0b04","name":"Code Maze","image":{"@type":"ImageObject","inLanguage":"en-US","@id":"https:\/\/code-maze.com\/#\/schema\/person\/image\/","url":"https:\/\/code-maze.com\/wp-content\/uploads\/2020\/01\/Code-Maze-Only-Logo-Transparent-HRez-150x150.png","contentUrl":"https:\/\/code-maze.com\/wp-content\/uploads\/2020\/01\/Code-Maze-Only-Logo-Transparent-HRez-150x150.png","caption":"Code Maze"},"description":"This is the standard author on the site. Most articles are published by individual authors, with their profiles, but when several authors have contributed, we publish collectively as a part of this profile.","sameAs":["https:\/\/www.linkedin.com\/company\/codemaze\/","https:\/\/x.com\/https:\/\/twitter.com\/CodeMazeBlog"],"url":"https:\/\/code-maze.com\/author\/codemazecontributor\/"}]}},"_links":{"self":[{"href":"https:\/\/code-maze.com\/wp-json\/wp\/v2\/posts\/73515","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/code-maze.com\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/code-maze.com\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/code-maze.com\/wp-json\/wp\/v2\/users\/6"}],"replies":[{"embeddable":true,"href":"https:\/\/code-maze.com\/wp-json\/wp\/v2\/comments?post=73515"}],"version-history":[{"count":6,"href":"https:\/\/code-maze.com\/wp-json\/wp\/v2\/posts\/73515\/revisions"}],"predecessor-version":[{"id":74123,"href":"https:\/\/code-maze.com\/wp-json\/wp\/v2\/posts\/73515\/revisions\/74123"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/code-maze.com\/wp-json\/wp\/v2\/media\/62189"}],"wp:attachment":[{"href":"https:\/\/code-maze.com\/wp-json\/wp\/v2\/media?parent=73515"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/code-maze.com\/wp-json\/wp\/v2\/categories?post=73515"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/code-maze.com\/wp-json\/wp\/v2\/tags?post=73515"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}