How to "mount" a multiple variable?

Asked

Viewed 154 times

1

Would it be possible to mount a variable to pass a value to it? For example:

var teste0 = "valor";
var teste1 = "outro valor";
var teste2 = "mais um valor";

for(int i=0;i<3;i++){
    teste+i = "mudou "+i;
}

Look at the teste+i. Even though I hoped it wouldn’t work, I tried it this way and I was wrong.

Is there any way I can assemble the variable as in the idea of the example?

  • There is no way you can mount a variable like this. Use arrays or collections for this.

  • 1

    If these variables are all of the same type, an array or a generic list resolves.

  • @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?

  • 1

    Since these variables deal with the same element, it might be interesting to create a class for them. Ex: Class Pessoa with properties Nome and DataNascimento. Then you use a List<Pessoa>

  • You really should rethink the logic by "mounting variable name".

  • @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

Show 1 more comment

3 answers

1

Yes, it is possible, it is one of the most basic and known techniques of programming. You do this with a variable of type array. A array is a variable that stores variables and so you can access them in exactly the same way, only the slightly different syntax.

Do not use a dictionary for this, it is totally unnecessary, slow, unproductive and insecure, even less use more complex reflection or solutions that have the same problems sharply (ie the solutions of the other two answers). Look how simple, safe and performative:

using static System.Console;

public class Program {
    public static void Main() {
        var teste = new string[] {"valor", "outro valor", "mais um valor" };
        for (var i = 0; i < 3; i++) teste[i] = "mudou " + i;
        foreach(var item in teste) WriteLine(item );
    }
}

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

0

I would recommend for this situation you use a string dictionary.

Dictionary<string, string> dictionary = new Dictionary<string, string>();
dictionary.Add("teste0", "valor");
dictionary.Add("teste1", "outro valor");
dictionary.Add("teste2", "mais um valor");

for(int i=0;i<3;i++) {
    Console.WriteLine(dictionary["teste" + i.ToString()]);
} 
  • 1

    This code will not compile. You are calling i.ToString() and not Teste + i. One must place between parentheses to execute the expression. In addition, i is not declared. for(i = 0 becomes for(int i = 0.

  • Fixed, famous Ctrl+c and Ctrl+v. Thank you.

-2

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!");
  • @Victorlaio the simple answer to this simple question is also simple: it is not possible to do this. Unless reflection is used, as in the example I mentioned, it will not be possible to dynamically change the reference of the variable without using reflection before.

  • @Cyberpotato It is that how you should know the used Reflection incorrectly can cause a major performance problem if it does not know where it is stirring, being something that it would easily solve in other ways. Although I do not recommend it is rather an alternative to the question.

  • @Victorlaireflection is slow when you use it to do things you wouldn’t need the same, just like any other instruction. https://answall.com/questions/13089/o-que%C3%A9-Reflection-by-which-%C3%A9-%C3%Batil-as-use

  • 1

    You and I both know that, but what about our friend who’s clearly in doubt about who’s starting development? He will not think 2x before assembling his whole routine within this method or adapt it to your need without knowing the risks you take

Browser other questions tagged

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