How to create properties dynamically in C#?

Asked

Viewed 844 times

10

In Javascript it is easy to create an object with new properties.

var obj = {
  "propriedade1" : "valor",
  "propriedade2" : "valor"
}

It is possible to do something similar in C#?

var lista = new List<Object>();

 foreach (var item in umaOutraList)
 {
      lista.Add(new Object()
      {
          nome = item.Nome //Essa linha não funfa.
      });
 }
  • 1

    Well @bigown in terms of solution, I had used Fernando’s tip. But with his answer now I could understand more deeply the concept. More important than making it work is to know why it’s working... and also use the best solution. Thank you!

4 answers

12

If this is really necessary in your code without having one class really, then you can use dynamic of the C# instead of object, doing something like that:

IList<dynamic> list = new List<dynamic>();
list.Add(new {
    nome = "Fernando",
    idade = 26,
});
  • 2

    It’s not necessary dynamic in this scenario. So' is dynamic if the intention is later to read the properties (and in that case, it is best to create a class of your own instead of using Anonymous types). If it is not necessary to read the properties, the best is List<object> instead of List<dynamic>

  • @dcastro, yes dynamic is not necessary if you do not wish to obtain the value of the property later, in that case object would be enough. But I only mentioned the dynamic by being but practical and having that purpose. And also I have no knowledge about major problems in using it rather than object. But your placement is valid.

7


Current responses do not simulate exactly what happens with JS. It can even achieve a similar (and not equal) result, but in a very different way. So it simulates correctly:

using static System.Console;
using System.Dynamic;
                    
public class Program {
    public static void Main() {
        dynamic obj = new ExpandoObject();
        obj.propriedade1 = "valor1";
        obj.propriedade2 = "valor2";
        WriteLine(obj.propriedade1);
        WriteLine(obj.propriedade2);
    }
}

Behold working in the ideone. And in the .NET Fiddle. Also put on the Github for future reference.

Documentation of ExpandoObject().

This way you can add and remove members in the object as you can in JS. You can manipulate everything dynamically as it is in JS, with a standard syntax of the language. Thus the object is created without having a class as a model, but it behaves as if it were a normal object of . NET.

It may not be necessary for the AP, but the premise of the question indicates this.

  • This is called Reflection?

  • 1

    This is not the reflection itself, but the mechanism that allows this to happen is the reflection with some help from the compiler.

5

Basically this is the Anonymous Type.

Example:

var umaOutraList = new List<String>();
umaOutraList.Add("1");
umaOutraList.Add("2");

var novaLista = umaOutraList.Select(x => new {
    Nome = x
});

foreach (var item in novaLista)
{
    Console.WriteLine(item.Nome);
}

Exit:

1

2

Csharppad DEMO

0

Using an anonymous object should work, just use new { nome = "" } instead of using new Object { nome = "" }.

Utilise dynamic as @Fernando suggested in his reply should also work.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.