It is not possible to do this, at least not in C#. However, you can use reflection for this, however, the variables will need to be public and static and outside the scope of void
.
public class Program {
// converta para propriedades
public static string teste0 {get; set;} = "valor";
public static string teste1 {get; set;} = "outro valor";
public static string teste2 {get; set;} = "mais um valor";
public static void Main(string[] args) {
for(int i = 0; i < 3; i++) {
string nomeVariavel = "teste" + i.ToString();
string value = "Alguma Coisa";
var propInfo = typeof(Program).GetProperty(nomeVariavel);
if (propInfo != null)
{
propInfo.SetValue(propInfo, value, null);
}
}
Console.WriteLine(teste0);
Console.WriteLine(teste1);
Console.WriteLine(teste2);
}
}
If you find it more convenient, you can make a small method for it:
public static void AlterarValor(Type objTipo, string varName, object value) {
var propInfo = objTipo.GetProperty(varName);
if (propInfo != null)
{
propInfo.SetValue(propInfo, value, null);
}
}
And wear it like this:
AlterarValor(typeof(Program), "teste0", "Olá, mundo!");
There is no way you can mount a variable like this. Use arrays or collections for this.
– Weiner Lemes
If these variables are all of the same type, an array or a generic list resolves.
– Ronaldo Araújo Alves
@Ronaldoaraújoalves are all the same type, but in case I’m getting them to move on to another one. For example,
var nome0 = "Ronaldo"; var data0 = "16/07/1995"; var nome1 = "Pedro"; var data1 = "16/07/1998"; for(int i=0; i<2;i++){ var frase = "O " nome+i + " nasceu no dia " data+i; }
. Something like that understands?– edro
Since these variables deal with the same element, it might be interesting to create a class for them. Ex: Class
Pessoa
with propertiesNome
andDataNascimento
. Then you use aList<Pessoa>
– Ronaldo Araújo Alves
You really should rethink the logic by "mounting variable name".
– Thiago Araújo
@edro Have any of the answers solved your question? Do you think you can accept one of them? Check out the [tour] how to do this, if you haven’t already done so. You would help the community by identifying what was the best solution for you. You can accept only one of them. But you can vote on any question or answer you find useful on the entire site
– Maniero