-2

I was searching for a solution for the problem I'm having in my project. In the link below I found something usefull:

One Key to multiple values dictionary in C#?

However: isn't it better to use a Object in the dictionary instead of using a Tuple??

Object obj = new Object();
var dict = new Dictionary<KeyType, obj>();
foreach(KeyType kt in dict)
{
  obj.X = value1;
  obj.Y = value2;
}

Instead of:

var dict = new Dictionary<KeyType, Tuple<string, int, int, int>>()

I hope that there is someone who could help me. Thanks :)

Community
  • 1
  • 1
E. Verdi
  • 310
  • 2
  • 19

3 Answers3

3

You cannot do obj.X in C#, if obj is of type Object. But you can create a custom class derived from Object, which contains all the field and properties you need and use it inside the dictionary.

This would indeed be superior to the Tuple solution, since myObj.Speed is much more descriptive than myTuple.Item2.

Note, however, that Tuples have some features that your custom class might not have, for example, tuple1.Equals(tuple2) returns true if both have the same elements. With your custom class, Equals will check for reference equality, unless you override it.

Heinzi
  • 167,459
  • 57
  • 363
  • 519
0

No, it is not better to use object - you loose your strong typing.

If you are concerned about the verbosity of your code, you can always do something like this:

At the top of your document:

using MyDictionary = Dictionary<KeyType, Tuple<string, int, int, int>>;

Then your constructors do this:

var dictionary = new MyDictionary();
dav_i
  • 27,509
  • 17
  • 104
  • 136
0

Instead of using Tuple I prefer to make a simple class with two/three fields. It's much cleaner solution and it's easier to use.

Koscik
  • 190
  • 1
  • 3
  • 14