How to dynamically create properties in C #?

9

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

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

Is it 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.
      });
 }
    
asked by anonymous 08.06.2015 / 19:38

4 answers

6

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

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);
    }
}

See working on dotNetFiddle .

ExpandoObject() documentation .

In 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 language syntax. So the object is created without having a class as a template, but it behaves as if it were a normal .Net object.

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

    
05.10.2015 / 06:05
11

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

IList<dynamic> list = new List<dynamic>();
list.Add(new {
    nome = "Fernando",
    idade = 26,
});
    
08.06.2015 / 19:46
5

Basically this is 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);
}

Output:

  

1

     

2

CSharpPad DEMO

    
08.06.2015 / 19:49
0

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

Using dynamic as @Fernando suggested in his response should also work.

    
08.06.2015 / 20:11