Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dynamically add properties to a existing object

Tags:

c#

I create the person object like this.

 Person person=new Person("Sam","Lewis") 

It has properties like this.

person.Dob
person.Address

But now I want to add properties like this and set the values at the run time after creating the object. person.Age person.Sex

How can I add those extra properties after creating the object. Those property name can be changed time to time. Therefor can't hardcode the "Age" and "Sex".

like image 666
Snj Avatar asked Jun 13 '11 10:06

Snj


People also ask

How do you add a dynamic property to an object?

Use the Record utility type to dynamically add properties to an object, e.g. const obj: Record<string, any> . The Record utility type constructs an object type, whose keys and values are of specific type. Copied! const obj: Record<string, any> = { name: 'Tom', }; obj.

How do you add properties to an existing object?

One way is to add a property using the dot notation: obj. foo = 1; We added the foo property to the obj object above with value 1.

Can we add dynamically named properties to JavaScript object?

In JavaScript, you can choose dynamic values or variable names and object names and choose to edit the variable name in the future without accessing the array. To do, so you can create a variable and assign it a particular value.


3 Answers

It's not possible with a "normal" object, but you can do it with an ExpandoObject and the dynamic keyword:

dynamic person = new ExpandoObject();
person.FirstName = "Sam";
person.LastName = "Lewis";
person.Age = 42;
person.Foo = "Bar";
...

If you try to assign a property that doesn't exist, it is added to the object. If you try to read a property that doesn't exist, it will raise an exception. So it's roughly the same behavior as a dictionary (and ExpandoObject actually implements IDictionary<string, object>)

like image 164
Thomas Levesque Avatar answered Oct 15 '22 03:10

Thomas Levesque


Take a look at the ExpandoObject.

For example:

dynamic person = new ExpandoObject();
person.Name = "Mr bar";
person.Sex = "No Thanks";
person.Age = 123;

Additional reading here.

like image 37
George Duckett Avatar answered Oct 15 '22 04:10

George Duckett


If you only need the dynamic properties for JSON serialization/deserialization, eg if your API accepts a JSON object with different fields depending on context, then you can use the JsonExtensionData attribute available in Newtonsoft.Json or System.Text.Json.

Example:

public class Pet
{
    public string Name { get; set; }
    public string Type { get; set; }

    [JsonExtensionData]
    public IDictionary<string, object> AdditionalData { get; set; }
}

Then you can deserialize JSON:

public class Program
{
    public static void Main()
    {
        var bingo = JsonConvert.DeserializeObject<Pet>("{\"Name\": \"Bingo\", \"Type\": \"Dog\", \"Legs\": 4 }");
        Console.WriteLine(bingo.AdditionalData["Legs"]);        // 4

        var tweety = JsonConvert.DeserializeObject<Pet>("{\"Name\": \"Tweety Pie\", \"Type\": \"Bird\", \"CanFly\": true }");
        Console.WriteLine(tweety.AdditionalData["CanFly"]);     // True

        tweety.AdditionalData["Color"] = "#ffff00";

        Console.WriteLine(JsonConvert.SerializeObject(tweety)); // {"Name":"Tweety Pie","Type":"Bird","CanFly":true,"Color":"#ffff00"}
    }
}
like image 11
warrickh Avatar answered Oct 15 '22 03:10

warrickh