C# is designed to be a statically typed language, i.e. when you define your type at compile time, you can’t change that type at . Which is the opposite to how Javascript operates.

However, with the recent addition of dynamic types and the Expando , it is possible to add a property to an as follows;

 dynamic c = new ExpandoObject();
 c.a = 1;
 c.b = 2;

However, one of the not-so things about the ExpandoObject, is that it doesn’t take a constructor argument, that would allow you to start off with an anonymous type, and then add some to it. This is where Clay comes in – which is a NUGET package you can install and reference as follows;

using ClaySharp; // Install-Package Clay

Then you can define much deeper types, and add properties to them.

dynamic New = new ClayFactory();

var person = New.Person(
FirstName: George,
LastName: Washington,
Country: new {
Name = United States,
Code = US

person.Sex = Male;
Console.WriteLine(person.FirstName +   + person.LastName +  is  + person.Sex);

That’s all great. However, you may notice, if you try to serialize the object to JSON using Newtsonsoft.JSON, or System.Web.Script.Serialization then you either get an error (Newtonsoft) or an empty string.

However, there is a similar project called Dynamitey which you can install using:

 Install-Package Dynamitey

And you change the line

dynamic New = new ClayFactory();


dynamic New = Builder.New();

This nuget package doesn’t seem to be compatible with .NET Core vNext (i.e. Mac), but it does create objects that are serialisable to JSON, like the following:

string output = JsonConvert.SerializeObject(person, Formatting.Indented);


  "FirstName": "George",
  "LastName": "Washington",
  "Country": {
    "Name": "United States",
    "Code": "US"
  "Sex": "Male"


Source link
thanks you RSS link


Please enter your comment!
Please enter your name here