AnxiousdeV
AnxiousdeV

Reputation: 373

How to create a class dynamically

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!

Upvotes: 4

Views: 2397

Answers (3)

Andrei Andrushkevich
Andrei Andrushkevich

Reputation: 9973

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.

Upvotes: -1

Stu
Stu

Reputation: 154

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

Upvotes: 1

Glenn Ferrie
Glenn Ferrie

Reputation: 10390

use the ExpandoObject to accomplish this.

dynamic dataTransferObject = new System.Dynamic.ExpandoObject();
dataTransferObject.Property1 = "someValue";
dataTransferObject.Property2 = "someOtherValue";

Upvotes: 7

Related Questions