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() { ... }
...
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) };
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With