4

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"]);
marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
r.zarei
  • 1,261
  • 15
  • 35

4 Answers4

6

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); }
    }
}
cyanic
  • 278
  • 1
  • 14
r.zarei
  • 1,261
  • 15
  • 35
  • This does what the question asks for, which is allowing you to reference any property within an object by "index." I can think of several situations where that would be useful. It is missing a major feature ofa true PropertyBag, in that it doesn't allow you to define and add new properties at runtime. Still +1 – Michael Blackburn Oct 26 '18 at 22:36
  • I'm not really sure of the benefit of accessing properties like this besides the syntax. The only way `TypeDescriptor.GetProperties(typeof(SomeClass))` will work is if the properties of `SomeClass` are `public`. I don't see any difference in accessing the property as `SomeClass["SomeProp"]` over `SomeClass.SomeProp`. Is there any benefit? – Jimenemex May 15 '19 at 21:31
  • @Jimenemex - There is no benefit in the case you show. The advantage comes when writing "dynamic" code, where the code might not even know the type of the object. Or the property name might be in a string, perhaps stored in some database, and be passed in to your code. Try to implement a method `object getProperty(object someOb, string somePropName)`. That's the spec you are given, now write a method that can do that - without knowing the object type. IMHO that is a very specialized need; usually one shouldn't be doing that to *any* object. Better to create a Dictionary, or use ExpandoObject. – ToolmakerSteve Nov 20 '21 at 02:05
3

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

nvoigt
  • 75,013
  • 26
  • 93
  • 142
  • i agree with u, however in some application there are situation where accessing properties like above can make code very readable and easier to work with. – r.zarei Apr 21 '13 at 13:04
1

This code would work

dynamic user= new ExpandoObject();
user.name = "Anonymous";
user.id=1234
user.address="12 broad way"
user.State="NY"

import System.Dynamic namespace.

OrganicCoder
  • 107
  • 1
  • 4
0

dynamic keyword can be used instead. Try yourself here

using System;
using System.Dynamic;
                    
public class Program
{
    public static void Main()
    {
        dynamic foo = new ExpandoObject();
        foo.Property = "simple string";
        Console.WriteLine(foo.Property);
    }
}
oleksii
  • 35,458
  • 16
  • 93
  • 163
  • can we use foo["Property"]="simple string"? – r.zarei Apr 21 '13 at 13:05
  • Unfortunately, to use `foo["Property"]` requires first casting to `IDictionary`. See https://stackoverflow.com/a/5611096/199364. – ToolmakerSteve Nov 20 '21 at 02:17
  • @ToolmakerSteve not sure what you mean. I've updated the answer with a working example – oleksii Nov 20 '21 at 10:10
  • Sorry, that was in response to r.zarei's old comment. Notice the syntax he used. This is useful if the **property name** is coming in as a string, for example from a database. Then it is not known at compile time, so can't do `foo.Property`. `foo["Property"]` isn't needed as is; the use case is `string prop = "Property"; ...other code...; foo[prop]` Dynamic languages (e.g. javascript) support this syntax; its a bit surprising that `dynamic` keyword does not. With `dynamic`, one has to do `string prop = "Property"; ... other code ...; var food = foo as IDictionary; food[prop]` – ToolmakerSteve Nov 20 '21 at 20:27
  • Or slightly more concise `((IDictionary)foo)[prop]`, if only need a single access. (I recently searched for what could be done with `dynamic` or with `ExpandoObject`, so added clarifying detail to related Q&A's.) – ToolmakerSteve Nov 20 '21 at 20:32
  • Oh, I see. It's also possible to use Reflection for this sort of thing or ORM frameworks if this is related to data access – oleksii Nov 21 '21 at 21:06