Thursday, March 31, 2011

Dynamic object properties in C# and Javascript

I have a table in the database for various settings in my application. These settings can be added to or changed at any time. I would like to pull them out of the db into an object and reference them in both my server code (C#) and client code (JS).

SettingGroup SettingName        type      value
Core         defaultPagingSize  numeric   5
Core         pagingType         text      dynamic
Ecommerce    showGallery        boolean   true

In javascript I can just put them into a JSON object and reference them like this:

var size = settings.core.defaultPagingSize;

Is there a similar way I can do this in C#?

int size = settings.core.defaultPagingSize;
From stackoverflow
  • No.

    The new dynamic keyword that will be added for .NET and C# 4.0 will handle what you're seeking, but in the current .NET and C# versions, there's no support for this.

    You should be able to get this to work though:

    int size = settings["core"]["defaultPagingSize"].ToInt32();
    

    or something similar.

  • In .NET, the most immediate answer would be to use a dictionary (perhaps nested) of some kind. C# 4.0 introduces some dynamic concepts, but you'd need to write a fair bit of code to get it to behave like javascript.

    Alternatively, store them as typed records in a flat list and use LINQ:

    var setting = settings.Single(x=>x.Group == "Core"
             && x.Name == "defaultPagingSize");
    int value = int.Parse(setting.Value);
    

0 comments:

Post a Comment