sonertbnc
sonertbnc

Reputation: 1720

How can i create anonymous object property from a string

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"
        }
    }

Upvotes: 1

Views: 2143

Answers (1)

ProgrammingLlama
ProgrammingLlama

Reputation: 38727

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

Upvotes: 4

Related Questions