Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to create properties on the fly, with a .NET dynamic object? [duplicate]

I'm trying to create a some Json in my MVC app and I only want to include the properties from my source object, if it has some properties values, set.

eg.

public class Foo
{
    public string Aaaa { get; set; }
    public string Bbbb { get; set; }
    public int? Ccccc { get; set; }
    public Lol Dddd { get; set; }
}

// Example Outputs.

  1. Aaaa and Ccccc have values only: return Json(new { Aaaa = source.Aaaa, Cccc = source.Ccccc.Value };

  2. Dddd only has been set. return Json(new { Dddd = source.Dddd }

See how i was trying to create an anonymous object on the fly. Well, I can do that because in this contrite example, I know what was set. But when it comes to real code, I would have to do 'figure out' what was really set and then dynamically return that.

The idea is based upon Stack Exchange's Api Wrapper .. where they have some optional values that they return via json, if they are set.

like image 871
Pure.Krome Avatar asked Feb 13 '12 11:02

Pure.Krome


People also ask

How do I add properties to ExpandoObject?

var x = new ExpandoObject(); x. AddProperty("NewProp", System. String);

What is dynamic object?

In C++, the objects can be created at run-time. C++ supports two operators new and delete to perform memory allocation and de-allocation. These types of objects are called dynamic objects. The new operator is used to create objects dynamically and the delete operator is used to delete objects dynamically.


1 Answers

Take a look at the ExpandoObject, an example with xml is given here

eg.

dynamic contact = new ExpandoObject();
contact.Name = "Patrick Hines";
contact.Phone = "206-555-0144";
... etc ...
like image 105
Henrik Gering Avatar answered Nov 16 '22 00:11

Henrik Gering