Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Return KeyValuePair or use out variable in C#?

Tags:

c#

I have a function that needs to return two strings. I've considered two different ways to do this:

string first = "this is first";
string second = "this is second";
KeyValuePair<string, string> ReturnPair()
{
    return new KeyValuePair<string, string>(first, second);
}
string ReturnOne(out string other)
{
    other = second;
    return first;
}

I would like to use the KeyValuePair<> approach but I feel that I am misusing the purpose for which this object was created.

My questions:

  1. Is there a better way to return 2 strings in this example?
  2. Is there anything wrong with returning the KeyValuePair?
like image 622
Guy Avatar asked Oct 08 '09 20:10

Guy


2 Answers

While there's nothing technically wrong with returning KeyValuePair, the thing you are returning is not conceptually a "key-value" pair. It's a simple pair.

Alternatively you can use a Tuple, which is available in .NET 4.0 or in the meantime, declare your own structure.

I normally advice against out parameters for returning tuples. Specially when you are using LINQ and functional language constructs, working with out parameters is tedious.

like image 173
mmx Avatar answered Sep 18 '22 08:09

mmx


If the data belongs logically together, but one is not logically the key of the other, I would define a new type that encapsulates it.

If one is a key to the other, I would use NameValuePair.

like image 37
Eric J. Avatar answered Sep 21 '22 08:09

Eric J.