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:
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With