Categories
allPost

How to create own dynamic type or dynamic object in C#?

497 people 👁️ing this randomly

How to create own dynamic type or dynamic object in C#?

How to create own dynamic type or dynamic object in C#? – Stack Overflow

Asked 9 years, 1 month ago

Try Adsterra Earnings, it’s 100% Authentic to make money more and more.

Try Adsterra Earnings, it’s 100% Authentic to make money more and more.

Viewed 263k times

There, is for example, ViewBag property of ControllerBase class and we can dynamically get/set values and add any number of additional fields or properties to this object, which is cool .I want to use something like that, beyond MVC application and Controller class in other types of applications. When I tried to create dynamic object and set it’s property like below:

1. dynamic MyDynamic = new { A=”a” }; 2. MyDynamic.A = “asd”; 3. Console.WriteLine(MyDynamic.A);

I’ve got RuntimeBinderException with message Property or indexer ‘f__AnonymousType0.A’ cannot be assigned to — it is read only in line 2. Also I suggest It’s not quite what I’m looking-for. Maybe is there some class which can allow me to do something like:

??? MyDynamic = new ???(); MyDynamic.A = “A”; MyDynamic.B = “B”; MyDynamic.C = DateTime.Now; MyDynamic.TheAnswerToLifeTheUniverseAndEverything = 42;

with dynamic adding and setting properties.

asked Oct 3 ’12 at 13:17

DmytroDmytro

15.3k2424 gold badges7272 silver badges123123 bronze badges

dynamic MyDynamic = new System.Dynamic.ExpandoObject(); MyDynamic.A = “A”; MyDynamic.B = “B”; MyDynamic.C = “C”; MyDynamic.Number = 12; MyDynamic.MyMethod = new Func(() => { return 55; }); Console.WriteLine(MyDynamic.MyMethod());

Read more about ExpandoObject class and for more samples: Represents an object whose members can be dynamically added and removed at run time.

answered Oct 3 ’12 at 13:21

Mario SMario S

11.2k2424 gold badges3636 silver badges4646 bronze badges

1

I recently had a need to take this one step further, which was to make the property additions in the dynamic object, dynamic themselves, based on user defined entries. The examples here, and from Microsoft’s ExpandoObject documentation, do not specifically address adding properties dynamically, but, can be surmised from how you enumerate and delete properties. Anyhow, I thought this might be helpful to someone. Here is an extremely simplified version of how to add truly dynamic properties to an ExpandoObject (ignoring keyword and other handling):

// my pretend dataset List fields = new List(); // my ‘columns’ fields.Add(“this_thing”); fields.Add(“that_thing”); fields.Add(“the_other”); dynamic exo = new System.Dynamic.ExpandoObject(); foreach (string field in fields) { ((IDictionary)exo).Add(field, field + “_data”); } // output – from Json.Net NuGet package textBox1.Text = Newtonsoft.Json.JsonConvert.SerializeObject(exo);

answered Aug 29 ’16 at 14:58

AlienFromCAAlienFromCA

7231111 silver badges1717 bronze badges

3

ExpandoObject is what are you looking for.

dynamic MyDynamic = new ExpandoObject(); // note, the type MUST be dynamic to use dynamic invoking. MyDynamic.A = “A”; MyDynamic.B = “B”; MyDynamic.C = “C”; MyDynamic.TheAnswerToLifeTheUniverseAndEverything = 42;

answered Oct 3 ’12 at 13:21

nothrownothrow

15.1k66 gold badges5151 silver badges100100 bronze badges

dynamic myDynamic = new { PropertyOne = true, PropertyTwo = false}; Andrew

15.1k99 gold badges8787 silver badges9898 bronze badges

answered Oct 17 ’19 at 15:19

smedasnsmedasn

9031010 silver badges1313 bronze badges

var data = new { studentId = 1, StudentName = “abc” };

Or value is present

var data = new { studentId, StudentName };

answered Nov 19 ’19 at 12:42

RockRock

40555 silver badges1414 bronze badges

1

You can use ExpandoObject Class which is in System.Dynamic namespace.

dynamic MyDynamic = new ExpandoObject(); MyDynamic.A = “A”; MyDynamic.B = “B”; MyDynamic.C = “C”; MyDynamic.SomeProperty = SomeValue MyDynamic.number = 10; MyDynamic.Increment = (Action)(() => { MyDynamic.number++; });

More Info can be found at ExpandoObject MSDN

answered Oct 3 ’12 at 13:55

Kishore KumarKishore Kumar

12.1k2626 gold badges9090 silver badges151151 bronze badges

dynamic MyDynamic = new ExpandoObject();

answered Oct 3 ’12 at 13:23

DaveczDavecz

1,17811 gold badge1818 silver badges4040 bronze badges

Your Answer

Thanks for contributing an answer to Stack Overflow!

  • Please be sure to answer the question. Provide details and share your research!

But avoid

  • Asking for help, clarification, or responding to other answers.
  • Making statements based on opinion; back them up with references or personal experience.

To learn more, see our tips on writing great answers.

Draft saved

Draft discarded

Post as a guest

lang-cs

{“use strict”;function j(a){return”string”==typeof a?document.getElementById(a):a}function k(a){return!!(a=j(a))&&”none”===getComputedStyle(a).display}function e(a){return!k(a)}function n(a){return!!a}function i(a){return /^s*$/.test(j(a).innerHTML)}function a(a){var b=a.style;b.height=b.maxHeight=b.minHeight=”auto”,b.display=”none”}function c(a){var b=a.style;b.height=b.maxHeight=b.minHeight=”auto”,b.display=”none”,[].forEach.call(a.children,c)}function l(a){var b=a.style;b.height=b.maxHeight=b.minHeight=”auto”,b.removeProperty(“display”)}function q(a,b){var c;return function(){return a&&(c=a.call(b||this,arguments),a=null),c}}function o(a){var b=document.createElement(“script”);b.src=a,document.body.appendChild(b)}function r(a,b){return a.push=function(a){return b(),delete this.push,this.push(a)},a}function x(){return”undefined”!=typeof googletag&&!!googletag.apiReady}function m(){var a;x()||(window.googletag={cmd:(a=g,r([],a))})}function b(a){var b=a.split(“_”)[0],c=u.ids[b],d=u.slots[c];return”function”==typeof d&&(d=d(b)),{path:”/248424177/”+h+”/”+c+”/”+p,sizes:d,zone:c}}function d(f){try{Array.isArray(clc.dfp.slotsRenderedEvents)||(clc.dfp.slotsRenderedEvents=[]),clc.dfp.slotsRenderedEvents.push(f);var g=f.slot.getSlotElementId(),e=[];g||e.push(“id=0”);var h=document.getElementById(g);if(g&&!h?e.push(“el=0”):h.hasAttribute(“data-clc-stalled”)&&e.push(“st=1”),0!==e.length)return void v(e.join(“&”));var j=b(g),k=(j.path,j.sizes,j.zone);if(clc.collapse&&clc.collapse[k]&&f.isEmpty)return h.id,c(h),void h.setAttribute(“data-clc-ready”,”true”);if(h.id,f.lineItemId,-1!==z.dh.indexOf(f.lineItemId))c(h);else if(f.lineItemId){h.setAttribute(“data-clc-prefilled”,”true”);var m=h.parentElement;if(m.classList.contains(“js-zone-container”)){switch(a(m),h.id,m.querySelectorAll(“.js-report-ad-button-container”)[0].style.height=”24px”,g){case”dfp-tlb”:case”dfp-tag”:m.classList.add(“mb8″);break;case”dfp-mlb”:case”dfp-smlb”:case”dfp-bmlb”:m.classList.add(“my8″);break;case”dfp-isb”:m.classList.add(“mt24″);break;case”dfp-m-aq”:m.classList.add(“my12”),m.classList.add(“mx-auto”);}l(m),l(h)}else l(h);”dfp-msb”==g&&c(document.getElementById(“hireme”))}h.setAttribute(“data-clc-ready”,”true”)}catch(a){var n=document.querySelector(“#dfp-tsb, #dfp-isb, #clc-tsb”);n&&n.setAttribute(“data-clc-ready”,”true”),v(“e=1”)}}function s(d,f){“dfp-isb”===d&&f.setTargeting(“Sidebar”,[“Inline”]),”dfp-tsb”===d&&f.setTargeting(“Sidebar”,[“Right”]);var e=b(d),g=e.path,h=e.sizes;e.zone,JSON.stringify(h);var a=googletag.defineSlot(g,h,d);a.addService(f);var c=d.split(“_”);if(“clc-cpa”==c[0]&&c[1]){var i=c[1];a.setTargeting(“talent-company-id”,i)}}window.clc=window.clc||{};var z=function(a,b){for(var c in b)a[c]=b[c];return a}({“lib”:”https://cdn.sstatic.net/clc/clc.min.js?v=9fb71081b5c6″,”style”:”https://cdn.sstatic.net/clc/styles/clc.min.css?v=86ebc1aa2ac9″,”u”:”https://clc.stackoverflow.com/markup.js”,”wa”:true,”kt”:2000,”tto”:true,”h”:”clc.stackoverflow.com”,”allowed”:”^(((talent\.)?stackoverflow)|(blog\.codinghorror)|(serverfault|askubuntu)|([^\.]+\.stackexchange))\.com$”,”wv”:true,”al”:false,”dh”:[5171832659],”abd”:true},clc.options||{}),t=q(function(){o(z.lib)});window.clc=window.clc||{},clc.cmd=clc.cmd||[];var f=clc.cmd;Array.isArray(clc.cmd)&&(0<clc.cmd.length?t():r(clc.cmd,t));var g=q(function(){z.targeting_consent||void 0===z.targeting_consent?o("https://securepubads.g.doubleclick.net/tag/js/gpt.js"):o("https://pagead2.googlesyndication.com/tag/js/gpt.js")}),p=/^/tags//.test(location.pathname)||/^/questions/tagged//.test(location.pathname)?"tag-pages":/^/$/.test(location.pathname)||/^/home/.test(location.pathname)?"home-page":"question-pages",h=location.hostname,u={slots:{lb:[[728,90]],mlb:[[728,90]],smlb:[[728,90]],bmlb:[[728,90]],sb:function(a){return"dfp-tsb"===a?[[300,250],[300,600]]:[[300,250]]},"tag-sponsorship":[[730,135]],"mobile-below-question":[[320,50],[300,250]],msb:[[300,250],[300,600]],"talent-conversion-tracking":[[1,1]]},ids:{"dfp-tlb":"lb","dfp-mlb":"mlb","dfp-smlb":"smlb","dfp-bmlb":"bmlb","dfp-tsb":"sb","dfp-isb":"sb","dfp-tag":"tag-sponsorship","dfp-msb":"msb","dfp-m-aq":"mobile-below-question","clc-tlb":"lb","clc-mlb":"mlb","clc-tsb":"sb","clc-cpa":"talent-conversion-tracking"}},v=function(a){new Image().src="https://"+z.h+"/stalled.gif?"+a};window.clc=window.clc||{},clc.options=z,clc.cmd=f,clc.dfp={load:function b(l){void 0===l&&(l=Object.keys(u.ids).filter(function(a){return"clc-cpa"!=a}));var o=["dfp-mlb","dfp-smlb"];if(!x())return m(),void googletag.cmd.push(function(){return b(l)});var q=function(a){var b=a.map(j).filter(n);return{eligible:b.filter(i).filter(e),ineligible:b.filter(k)}}(l),r=q.eligible,f=q.ineligible;if(r.forEach(function(b){a(b)}),f.forEach(c),0!==r.length){var g;z.abd&&((g=document.createElement("div")).className="adsbox",g.id="clc-abd",g.style.position="absolute",g.style.pointerEvents="none",g.innerHTML=" ",document.body.appendChild(g));var p=googletag.pubads().getSlots().filter(function(a){return 0o.indexOf(a.id)}),v=r.filter(function(a){return!!z.ll&&0 Stack Overflow works best with JavaScript enabled

Your privacy

By clicking “Accept all cookies”, you agree Stack Exchange can store cookies on your device and disclose information in accordance with our Cookie Policy.

 


More Story on Source:

*here*

How to create own dynamic type or dynamic object in C#?

Dillard's - The Style of Your Life.

By allaboutian

open profile for all

Related Posts

Agen Slot Gacor Terbaru: Panduan Memilih dan Bermain di Situs Terpercaya

38 people 👁️ing this randomly Industri perjudian online terus berkembang pesat, khususnya di Indonesia. Salah…

CrackStreams – Overview NFL, MMA, NBA, Boxing HD UFC 

317 people 👁️ing this randomly Welcome to CrackstreamsLinks are updated ONE day BEFORE the event.…

New Zealand limited-overs tour of Australia postponed

3,169 people 👁️ing this randomly New Zealand limited-overs tour of Australia postponed News Try Adsterra…