0

On an ASP.net tutorial, I found this explanation for List<>,

List<string> users = new List<string>();

I have a chatroom, where each user has IP, connectionid, and nick. So I need three string variables. Is it possible to store three variables per item in a list or should I use something else?

Confusion
  • 16,256
  • 8
  • 46
  • 71

1 Answers1

10

That's when you use a class or a struct:

class User
   public string IP { get; set; }
   public string ConnId { get; set; }
   public string Nick { get; set; }
}

And use this in a list:

List<User> users = new List<User>();

Now you can create a user as such:

users.Add(new User { IP = "some ip", ConnId = "some id", Nick ="Jeroen" });

Or if you hate classes and want to go rough:

var users = new List<Tuple<string, string, string>>();
users.Add(new Tuple<"some ip", "some id", "Jeroen">);

This last option is particularly easy when you'll just use it in one place and don't expect any changes to it. It allows you to quickly group some related data.

Jeroen Vannevel
  • 43,651
  • 22
  • 107
  • 170
  • Don't be lazy, do not use tuple, it becomes a readability nightmare later on. – PCG Dec 07 '13 at 04:36
  • @PCG: depending on the use case it might very well be suitable. I agree it shouldn't be the first choice though, just adding it to spice things up from the usual checklist. – Jeroen Vannevel Dec 07 '13 at 04:37