Home > Mobile >  Create an class or an object that can have different properties everytime in C#
Create an class or an object that can have different properties everytime in C#

Time:10-29

I have a class which has a property named properties but that property can have different values. Those are dynamic values coming from somewhere and I need to create a request with a structure of Json which has Customer and properties can have different values. I tried the following:

Customer Class

public class Customer{
  public string name {get;set;}
  public dynamic properties {get;set;}
}

These properties can be dynamic. For example - This can be the json that I get

1st Example:

"properties":{
  "name": "Mark",
  "address": {
    "city":"paris"
   }
}

2nd Example:

"properties":{
  "name": "Chris",
  "description":"human",
  "birth":"1990",
  "address": {
    "name":"paris"
   }
}

Whenever I do properties.address.name, it says it can refer to the null reference. I am not sure if dynamic type is correct. How this should be done in C#. If the property can have different values, what is the approach you take?

CodePudding user response:

Dynamic types are complex but in short, they are evaluated in run time instead of compile time (see: https://www.geeksforgeeks.org/dynamic-type-in-c-sharp/). It doesnt seem like this is what you are dealing with and you can simplify the solution.

It looks like there are many answers to your question (short google came up with: Add properties dynamically at run time in existing class c# and many more) which you can try and implement.

However - maybe it would be easier to use json supporting packages like newtonsoft.json and have a json object as Properties.

Then you would be able to both add and use the json elements (properties):

using Newtonsoft.Json;

public class Customer 
{   
   public string Name {get;set;}   
   public JObject Properties {get;set;} = new JObject();
}

Add with:

customer.Properties["evilProp"] = 666;

And get it with:

var numberFromHell = customer.Properties["evilProp"];
  • Related