Is it possible to add attributes to a property of dynamic object runtime?
Asked Answered
T

1

12

I want to add an attribute to property of a dynamic object/expando object runtime, is it possible?

What I would like to do is:

dynamic myExpando = new ExpandoObject();
myExpando.SomeProp = "string";
myExpando.AddAttribute("SomeProp", new MyAttribute());

Is it possible to do that in one way or another?

Tellurium answered 11/12, 2013 at 21:19 Comment(5)
why don't you run that code and see?Enuresis
Have you checked out TypeDescriptor? msdn.microsoft.com/en-us/library/…Scopp
@SamIam: I don't think he expects it to work, but to be explicit, no. It does not work. The result is this: RuntimeBinderException: 'System.Dynamic.ExpandoObject' does not contain a definition for 'AddAttribute'Estrada
#564048 might also helpScopp
@user2720372: Not a duplicate. That doesn't help with attributes.Estrada
T
1

You can add an attribute to a dynamic object like this:

 dynamic myExpando = new ExpandoObject();
            myExpando.SomeProp = "string";
            TypeDescriptor.AddAttributes(myExpando, new SerializableAttribute());

To read the attributes you should use this:

 dynamic values = TypeDescriptor.GetAttributes(myExpando);
            for (int i = 0; i < values.Count; i++)
            {
                System.Console.WriteLine(values[i]);
            }

I am not sure you can read custom attributes like that. However you can also try reflection:

 System.Reflection.MemberInfo info = myExpando.GetType();
            object[] attributes = info.GetCustomAttributes(true);
            for (int i = 0; i < attributes.Length; i++)
            {
                System.Console.WriteLine(attributes[i]);
            }

However, with reflection you cannot see the attribute that you have been added because attributes are static metadata.

TypeDescriptor is a metadata engine provided by the .NET FCL. You can read the article here:

http://blogs.msdn.com/b/parthopdas/archive/2006/01/03/509103.aspx

Thales answered 11/12, 2013 at 22:13 Comment(1)
But this is adding the property to the type and not to the property.Tellurium

© 2022 - 2024 — McMap. All rights reserved.