Adding methods to ExpandoObjects
Asked Answered
D

2

6

UPDATE

The problem is not the code, the problem is that you apparently can't evaluate dynamic objects from the immediate window.


I'm trying to tack on methods to an ExpandoObject but not sure how to get it to work. Here's my code:

dynamic myObj = new ExpandoObject();
myObj.First = "Micah";
myObj.Last = "Martin";
myObj.AsString = new Func<string>(() => myObj.First + " " + myObj.Last);

//No matter what I do I get 'object' does not contain a definition for 'AsString'
myObj.AsString;
myObj.AsString();
myObj.AsString.Invoke();

Anyone know how to do this?

Dunkle answered 16/9, 2010 at 14:15 Comment(0)
S
9

Are you sure you included all the code?

I just tested and ran the following and was successful:

dynamic obj = new ExpandoObject();

obj.First = "Hello";
obj.Last = "World!";

obj.AsString = new Func<string>(() => obj.First + " " + obj.Last);

// Displays "Hello World!"
Console.WriteLine(obj.AsString());
Shavers answered 16/9, 2010 at 14:25 Comment(1)
Strange. It does work when you run it, it just doesn't work when you try to call it from the Immediate Window. Thanks!Dunkle
B
0

The compiler will complain about

myObj.AsString; // only assignment, call, increment, decrement, and new object expressions can be used as a statement

So get rid of it. And of course get rid of the line of code that you say does not compile. However, the rest of your code should work once those bits are fixed. Example (plus adding another "method"):

dynamic myObj = new ExpandoObject();
myObj.First = "Stack";
myObj.Last = "Overflow";

Action<int> PrintInt = input => Console.WriteLine(input.ToString());
myObj.PrintInt = PrintInt;
myObj.PrintInt(1);

myObj.AsString = new Func<string>(() => myObj.First + " " + myObj.Last);
string s = myObj.AsString();
Console.WriteLine(s);
Brooksbrookshire answered 16/9, 2010 at 14:27 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.