Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Initialize tuple with empty or null values in C#

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>("","");
like image 404
rajibdotnet Avatar asked Nov 21 '12 20:11

rajibdotnet


2 Answers

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;
}
like image 87
Dave Zych Avatar answered Sep 21 '22 06:09

Dave Zych


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;
like image 30
fsimonazzi Avatar answered Sep 22 '22 06:09

fsimonazzi