Julian42_74
Julian42_74

Reputation: 43

How do I write the name of a variable in a list in c#?

I have some code that moves variables around within a list, and I would like to write the name of a variable based on where it is located within the list.

This is what I tried:

        int var1 = 4;
        int var2 = 6;
        int var3 = 12;

        List<int> List = new List<int>() { var1, var2, var3 };
        Console.WriteLine(nameof(List[1]));

I cannot (or at least I don't think I can) just write Console.WriteLine(nameof(var2)); because that will write var2 every time, but I want to be able to write the name of the second variable, even if I move the location of each variable around.

Any help would be greatly appreciated :)

Upvotes: 2

Views: 2793

Answers (4)

EL Khayar
EL Khayar

Reputation: 11

public Class Elements
{ 
    public string Name{get; set;}
    public int ID {get; set;}
}

static main void ()
{      
    var element1 = new Elements(){ Name = var1, ID= 4};
    var element2 = new Elements(){ Name = var2, ID= 6};
    var element3 = new Elements(){ Name = var3, ID= 12};
           
    var list = new List<Elements>() { element1, element2, element3 };
    foreach(var e in list)
    { 
        Console.WriteLine(e.Name);
    }
}

Upvotes: 0

Md. Sabbir Ahamed
Md. Sabbir Ahamed

Reputation: 485

Oakley is right. But I love dictionary in that case, because it's pretty simple and good in performance. Just check out the code.

Dictionary<string, int> dictionary = new Dictionary<string, int>();

dictionary.Add("var1", 4);
dictionary.Add("var2", 6);
dictionary.Add("var3", 12);

foreach (var i in dictionary)
{
    System.Console.WriteLine(i.Key);
}

If you want that Key and Value could be any data type. Then you can use the following.

Dictionary<object, object> dictionary = new Dictionary<object, object>();

Upvotes: 1

Idle_Mind
Idle_Mind

Reputation: 39142

Another approach would be to simply create your own CLASS to hold the two values and make a List of that instead:

public class Data
{
    public String Name;
    public int Value;
}

public static void Main(string[] args)
{
    List<Data> data = new List<Data>();
    data.Add(new Data { Name = "var1", Value = 4 });
    data.Add(new Data { Name = "var2", Value = 6 });
    data.Add(new Data { Name = "var3", Value = 12 });
    Console.WriteLine("1: " + data[1].Name);

    data.Insert(1, new Data { Name = "newVar", Value = 5 });
    Console.WriteLine("1: " + data[1].Name);
    Console.WriteLine("2: " + data[2].Name);

    Console.WriteLine("Press Enter to Quit");
    Console.ReadLine();
}

Upvotes: 0

Wellerman
Wellerman

Reputation: 856

List does not store the actual variable, just the value of it. If you are wanting to store names and values, you'll want to use a dictionary or a list of KeyValuePairs instead, setting the 'name' to be the key and the value as the value.

Upvotes: 5

Related Questions