Home > Uncategorized > Adding properties at #runtime to an object in C#

Adding properties at #runtime to an object in C#

clay

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 runtime. Which is the opposite to how Javascript operates.

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

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

However, one of the not-so good 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 properties 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();

to

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);

giving:

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

 

Advertisement
Categories: Uncategorized
  1. No comments yet.
  1. No trackbacks yet.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: