Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Property bag for C# class

Accessing c# class properties like javascript language would make life a lot easier.

How we can do it in C#?

For example:

someObject["Property"]="simple string";
Console.WriteLine(someObject["FirstName"]);
like image 951
r.zarei Avatar asked Jan 14 '23 14:01

r.zarei


2 Answers

Here is how you can enable property-bag-like functionality in your classes by adding a few lines of code:

partial class SomeClass
{
    private static readonly PropertyDescriptorCollection LogProps = TypeDescriptor.GetProperties(typeof(SomeClass));

    public object this[string propertyName]
    {
        get { return LogProps[propertyName].GetValue(this); }
        set { LogProps[propertyName].SetValue(this, value); }
    }
}
like image 181
r.zarei Avatar answered Jan 23 '23 13:01

r.zarei


You could derive every single class from Dictionary<string, object>. But then, you could simply take JavaScript instead of misusing C#.

like image 22
nvoigt Avatar answered Jan 23 '23 14:01

nvoigt