4

I need to create a class object dynamically. I attempted this using the dynamic keyword.

dynamic dataTransferObject = new dtoClass();
                dataTransferObject.Property1= "someValue";
                dataTransferObject.Property2= "someOtherValue";

                LogicLayer.Update(dataTransferObject);

I will interpret the object to perform further action inside of the logic layer. The compiler does not like my syntax, please advise!

2
  • Does dtoClass exist at compile time or only at run time? Commented Jul 5, 2011 at 19:12
  • This object will only exist at runtime. Commented Jul 5, 2011 at 19:22

3 Answers 3

7

use the ExpandoObject to accomplish this.

dynamic dataTransferObject = new System.Dynamic.ExpandoObject();
dataTransferObject.Property1 = "someValue";
dataTransferObject.Property2 = "someOtherValue";
Sign up to request clarification or add additional context in comments.

1 Comment

I'm looking into this now, seems to be what I am after
1

I think this might be what you're looking for!

http://www.hanselman.com/blog/NuGetPackageOfTheWeek6DynamicMalleableEnjoyableExpandoObjectsWithClay.aspx

Go to the section called "Expandos and Dynamic" - it allows you to do the following:

var person = New.Person();
person.FirstName = "Louis";
person.LastName = "Dejardin";

Stu

2 Comments

This is great info, I can foresee myself using the ClayFactory, very nice!
Yeah - it builds on the Expando stuff but gives you a much cleaner syntax. Messing around with it is on my to-do list too.
-1

try to use anonymous type. check following code:

var v = new { Property1 = "someValue", Property2 = "someOtherValue" };

Anonymous types provide a convenient way to encapsulate a set of read-only properties into a single object without having to explicitly define a type first.

3 Comments

The problem is that this object will be passed to another logical layer, and I am not sure if it will be interpreted correctly?
maybe it will be better to use interface for this issue
However, anonymous types are internal and can't pass assembly boundaries.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.