Haddar Macdasi
Haddar Macdasi

Reputation: 3555

Providing a DynamicObject properties

I need a way to provide a Dynamic get members and set for a given class. I want to be able to write code like this:

ns1.Resource.Field1 = "Hello";
string myField = ns1.Resource.Field1;

where ns1 is the namespace and I believe that "Resource" is the class name and Field1 or any other property is dynamic. So how do I declare a class like this ?

I've learned about inheriting Resource class from "DynamicObject" but its forcing me to instantiate the class Resource to an object, an operation I don't want to do.

Edit#1:
I want to create a way to use class like this:

Namespace.Resource.DynamicField = "Value";
string myValue = Namespace.Resource.DynamicField;

The "Resource" should not be instantiated and the DynamicField is a member that my class will be able to handle the get and set calls on it, so If at some place in code I write

Namespace.Resource.DynamicField2 = "Hello";

I will have a place where I can override the set call of to the static property "DynamicField2" of Resource. But I don't know in advanced the complete properties list of the class, So I need the properties to be dynamically created and be able to control the get and set like it was passed by "Name" let's say:

public class Resource{

   public static getMember(string Name){
       console.log(Name); //=> this will output "DynamicField2"
       return this.dictionary["Name"];
   }
}  

and then use it someplace at code

string a = Resource.DynamicField2; // a will be value "Hello" 

Upvotes: 0

Views: 182

Answers (2)

Yair Halberstadt
Yair Halberstadt

Reputation: 6891

Take a look at ExpandoObject:

https://learn.microsoft.com/en-us/dotnet/api/system.dynamic.expandoobject?view=netframework-4.7.2

It should serve your needs.

EDIT.

You could create a static property in the Resource class to access a singleton instance of the ExpandoObject.

Eg

public static class Resource
{
     public static dynamic Data {get;} = new ExpandoObject();
}

Then simply set Resource.Data.Field1 = whatever; etc.

Upvotes: 1

amir mehr
amir mehr

Reputation: 75

I don't exactly understand what you mean . But if you want to have a value like that (without creating an object) . You can declare your class and var as static like this:

namespace ns1{

public static class Resource {

    public static string Field1 = "hello-f1";
    public static string Field2 = "hello-f2";
}}

after that you can use this variable by call that Note that the Fields variable is not const so you can change it everywhere

Upvotes: 0

Related Questions