Access Object Property with a string

Asked

Viewed 999 times

4

Pupil:

public class Aluno{
     public int Id { get; set; }
     public string Nome { get; set; }
     public string Sobrenome { get; set; }
}

Now I need to access the student’s Name and Surname through a string, how can I do this?

EX.:

string opcaoA = "Nome";

var resultado = Aluno + ".opcaoA ";
//Resultado = "João";
  • I think it’s impossible! Object attributes and strings are not equivalent. C# is not javascript.

  • @Michaelpacheco This is possible and is very common. It is called Reflection.

  • @jbueno Very interesting!

1 answer

6


If I understand your question correctly, you can use Reflection, follow a practical example to help you:

Class

public class Cidade
{
    public string Nome { get; set; }
}

Static Method to Take Property Value

public static object PegaValorPropriedade(object obj, string propName)
{
    return obj.GetType().GetProperty(propName).GetValue(obj, null);
}

Page

protected  void Page_Load(object sender, EventArgs e)
{
    var cid = new Cidade();
    cid.Nome = "Jose";
    object ed = PegaValorPropriedade(cid, "Nome");
    Response.Write(ed.ToString());
    //Imprime José
}
  • Perfect friend! Wow, I’ve been trying to solve this problem for a long time! Helped from ++ Thanks!

  • Show, don’t forget to evaluate and close the question. ;)

Browser other questions tagged

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