Question

I search on Google but the result is misunderstand.
This is a code flow:

public class Store
{
     public dynamic GetList(List<string> propertyFields)
     {
          // Body here
          // for in list propertyFields. Such as: ["Code", "Name", "Address", ...]
          // dynamic result = ...
          // result.Code = "value", result.Name = "abc", result.Address = "homeless", result.... = "..."
          // return result
     }
}

Method returns a dynamic object.
propertyFields is a list of fields name. When I pass 4 strings in list, dynamic has 4 property fields with value (later).
When I call this method:

Store store = new Store(); 
var rs = store.GetList(["Code","Name","Address"])
Console.WriteLine(rs[0].Code)

That is my point.
My question: Is it possible to do that in C#?

Was it helpful?

Solution

You have confused dynamic, which is a compiler feature that means "defer type analysis of uses of this object until runtime" with ExpandoObject which means "an object that can have properties added at runtime".

It is an understandable confusion; many languages that lack static type checking also have expando objects.

OTHER TIPS

You need to take a look to ExpandoObject class.

Here is more detailed answer to your question:

Dynamic class creation

What are the true benefits of ExpandoObject?

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top