Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I define a method in an anonymous type?

Tags:

c#

.net

How do I go about defining a method, e.g. void doSuff() in an anonymous type? All documentation I can find uses only anonymous restricted basically to property lists. Can I even define a method in an anonymous type?

EDIT: OK, a quick look at very quick answers tells me this is impossible. Is there any way at all to construct a type dynamically and add an anonymous method to a delegate property on that type? I'm looking for a C# way to accomplish what the following JavaScript does:

...
person.getCreditLimit = function() { ... }
...
like image 325
ProfK Avatar asked Dec 12 '25 20:12

ProfK


2 Answers

Well, you can. With delegates you just treat methods as data:

var myMethods = from x in new[] { "test" }
                select new { DoStuff = new Func<string>(() => x) };

var method = myMethods.First();
var text = method.DoStuff();

What do you think the value of "text" is?

With the Action<> and Func<> generic types you can put (almost) whatever you want in there. Almost, because you cannot for instance access other properties on the anonymous type, like this:

var myMethods = from x in new[] { "test" }
                select new { Text = x, DoStuff = new Func<string>(() => Text) };
like image 102
Peter Lillevold Avatar answered Dec 15 '25 08:12

Peter Lillevold


You absolutely can, with delegates:

Action action = MethoThatDoesSomething;
var obj = new
          {
              DoSomething = action
          };

obj.DoSomething();

I tried with a lambda in the new { ... } and that didn't work, but the above is totally fine.

like image 42
Neil Barnwell Avatar answered Dec 15 '25 10:12

Neil Barnwell



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!