0

I want to create Key/Value Pair but with only one Set, not Dictionary with multiple pairs. (I don't want to use Array of size 2.)

What is the best way to do in C#?

JharPaat
  • 321
  • 1
  • 2
  • 12
  • 1
    You already have two answers: KeyValuePair and Tuple. Especially for Tuple I'd consider to use a custom type where members have proper name. Note they're similar but if performance are (really, in a measured way) important then you should carefully pick right one (one is a value type, the other a reference type). – Adriano Repetti Sep 24 '15 at 07:51
  • You already mentioned the answer in your question. if you would have typed Key/ValuePair c# in google, suprise! – Bgl86 Sep 24 '15 at 07:52

3 Answers3

2

You're looking for a KeyValuePair<TKey, TValue>:

var keyValuePair = new KeyValuePair<int, int>(1, 1);
Yuval Itzchakov
  • 146,575
  • 32
  • 257
  • 321
2

The Tuple should do what you are after:

Provides static methods for creating tuple objects.

Alternatively, you could always roll your own custom objects which has 2 fields.

npinti
  • 51,780
  • 5
  • 72
  • 96
1

For temporary/internal use you can do with anonymous object:

  var item = new {
    name = "myName",
    value = 456
  };
Dmitry Bychenko
  • 180,369
  • 20
  • 160
  • 215