11

I have this dictionary and tuples set up in SetValue() as below :-

var myDict = new Dictionary<string, Tuple<string, string>>();

private void SetValue() 
{
  var myTuple1= Tuple.Create("ABC", "123");
  var myTuple2= Tuple.Create("DEF", "456");
  myDict.Add("One", myTuple1)
  myDict.Add("Two", myTuple2)
}

I am trying to retrive the tuple in GetValue() as below :-

private void GetValue()
{
  var myTuple = new Tuple<string, string>("",""); //Is this correct way to initialize   tuple
  if (myDict.TryGetValue(sdsId, out myTuple))
  {
    var x = myTuple.Item1;
    var y = myTuple.Item2;
   }
}

My question is whether this is the correct way to initialize tuple while retrieving the same from a dictionary ? Is there a better code?

 var myTuple = new Tuple<string, string>("","");
kmatyaszek
  • 19,016
  • 9
  • 60
  • 65
rajibdotnet
  • 1,498
  • 2
  • 17
  • 29
  • Initializing a tuple has no direct relationship to using a dictionary. The two classes are not related. – usr Nov 21 '12 at 20:37

2 Answers2

21

If it's an out parameter, the object doesn't need to be initialized before being used. You should just be able to do:

Tuple<string,string> myTuple;
if (myDict.TryGetValue(sdsId, out myTuple))
{
    var x = myTuple.Item1;
    var y = myTuple.Item2;
}
Dave Zych
  • 21,581
  • 7
  • 51
  • 66
19

You don't need to create an instance for an out parameter. Just declare the local variable as Tuple but don't assign a value.

Tuple<string, string> myTyple;
fsimonazzi
  • 2,975
  • 15
  • 13
  • @TimSchmelter I honestly read the question as asking for the best way to define the variable for use in that scenario. As such, it just needed to be declared. – fsimonazzi Nov 21 '12 at 20:44