1

I want to create anonymous object with property which send as a string. Is that possible with reflection or something (from string to anonymous property)

 class Program
    {
        static void Main(string[] args)
        {

            object myobject = CreateAnonymousObjectandDoSomething("myhotproperty");
        }

        public static object CreateAnonymousObjectandDoSomething(string myproperystring)
        {
            //how can i create anonymous object from myproperystring
            return new { myproperystring = "mydata" }; //this is wrong !!
            // i want to create object like myhotproperty ="mydata"
        }
    }
3
  • So you want to create a copy of "mydata" of type object?? I don't get it Commented Jul 4, 2018 at 11:19
  • Consider using Dictionary<string, object> (property name, property value) Commented Jul 4, 2018 at 11:24
  • 1
    ... or ExpandoObject Commented Jul 4, 2018 at 11:24

1 Answer 1

4

It looks like you're trying to do something like this:

public static dynamic CreateAnonymousObjectandDoSomething(string mypropertystring)
{
    IDictionary<string, object> result = new ExpandoObject();
    result[mypropertystring] = "mydata";
    return result;
}

ExpandoObject is basically a dictionary that, when used with dynamic, can be used like a type.

Example:

var test = CreateAnonymousObjectandDoSomething("example");
Console.WriteLine(test.example);

Try it online

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.